我参考此链接创建了一个 api 它以下列方式验证请求:
router.post('/authenticate', function(req, res) {
var query = "SELECT * FROM ?? WHERE ??=? and ??=? LIMIT 1";
var table = ["users","user_email",req.body.user_email, "user_password",md5(req.body.user_password)];
query = mysql.format(query,table);
connection.query(query,function(err,rows){
if(err) {
res.json({"Error" : true, "Message" : "Error executing MySQL query"});
} else {
if(rows.length > 0){
var user = {'user_email':rows.user_email, 'user_password':rows.user_password}
var token = jwt.sign(user, app.get('superSecret'), {
expiresIn: '24h' // expires in 24 hours
});
delete rows[0].user_password;
// return the information including token as JSON
res.status(200).json({
error: false,
message: 'success',
token: token,
user:rows
});
} else {
res.status(404).json({"Error" : true, "Message" : "No records found"});
}
}
});
});
router.post("/users",function(req,res){
req.checkBody({
'user_email': {
notEmpty: true,
isEmail: {
errorMessage: 'Invalid Email'
}
},
'user_password': {
notEmpty: true,
isLength: {
options: [{ min: 6, max: 10 }],
errorMessage: 'Password must be between 6 and 10 chars long' // Error message for the validator, takes precedent over parameter message
},
errorMessage: 'Invalid Password' // Error message for the parameter
},
'user_name': { //
notEmpty: true, // won't validate if field is empty
isLength: {
options: [{ min: 2, max: 10 }],
errorMessage: 'Must be between 2 and 10 chars long' // Error message for the validator, takes precedent over parameter message
},
errorMessage: 'Invalid User Name'
},
'phone_number': { //
notEmpty: true,
isLength: {
options: [{ min: 10, max: 15}],
errorMessage: 'Must be between 10 and 15 chars long' // Error message for the validator, takes precedent over parameter message
},
errorMessage: 'Invalid Phone Number'
},
'address': { //
notEmpty: true,
isLength: {
options: [{ min: 10, max: 100}],
errorMessage: 'Must be between 10 and 100 chars long' // Error message for the validator, takes precedent over parameter message
},
errorMessage: 'Invalid Address'
},
'device_type': { //
notEmpty: true,
errorMessage: 'Invalid device type'
},
'login_type': { //
notEmpty: true,
errorMessage: 'Invalid login type'
},
'gcm_user_id': { //
notEmpty: true,
errorMessage: 'Invalid gcm id'
}
});
var errors = req.validationErrors();
if (errors) {
res.status(500).json(errors);
return;
}
var query = "INSERT INTO ??(??,??,??,??,??,??,??,??) VALUES (?,?,?,?,?,?,?,?)";
var table = ["users","user_name", "user_email", "user_password", "phone_number", "address", "device_type", "login_type", "gcm_user_id",
req.body.user_name, req.body.user_email, md5(req.body.user_password), req.body.phone_number, req.body.address,
req.body.device_type, req.body.login_type,req.body.gcm_user_id];
query = mysql.format(query,table);
connection.query(query,function(err,record){
if(err) {
res.status(500).json({"Error" : true, "Message" : err.message});
} else {
var query = "select * from ?? WHERE ?? = ?";
var table = ["users", "id", record.insertId];
query = mysql.format(query,table);
connection.query(query,function(err,rows){
if(err) throw err;
res.status(200).json({"Error" : false, "message" : "User Added !", "data":rows});
});
}
});
});
// route middleware to verify a token
router.use(function(req, res, next) {
// check header or url parameters or post parameters for token
var token = req.headers['x-access-token'];
console.log(token,'token');
// decode token
if (token) {
// verifies secret and checks exp
jwt.verify(token, app.get('superSecret'), function(err, decoded) {
if (err) {
console.log(err);
return res.json({ success: false, message: 'Failed to authenticate token.' });
} else {
// if everything is good, save to request for use in other routes
req.decoded = decoded;
next();
}
});
} else {
// if there is no token
// return an error
return res.status(401).send({
success: false,
message: 'No token provided.'
});
}
});
我想通过以下方式验证请求:
例子:
router.get("/users", jwtValidate ,function(req,res)
目前为了避免身份验证,我必须在中间件上方应用路由。