流程图
依赖项
"dependencies": {
"express": "^4.12.3",
"jsonwebtoken": "^5.0.0",
"mongoose": "^4.0.2",
"redis-fast-driver": "0.0.9",
}
获取token代码
function get_interface_token(req, res) {
Jiekou.findOne({username: req.query.username}, function (err, interface_find) {
if (err) throw err;
if (!interface_find) {
res.json({success: false, message: ‘认证失败,用户名找不到‘});
} else if (interface_find) {
if (interface_find.password != req.query.password) {
res.json({success: false, message: ‘认证失败,密码错误‘});
} else {
var time = new Date();
interface_find.token_create_time = time;
var token = jwt.sign(interface_find, config.secret, {
expiresInMinutes: 1440
});
r.rawCall([‘hmset‘, req.query.username, ‘token‘, token], function (err, d) {
if (err) throw err;
});
r.rawCall([‘EXPIRE‘, req.query.username, config.token_expire_time], function (err, d) {
if (err) throw err;
});
res.json({
success: true,
message: ‘Enjoy your token!‘,
token: token
});
}
}
})
}
检测token代码
function checktoken(req, res, next) {
var token = req.body.token || req.query.token || req.headers[‘x-access-token‘];
if (token) {
jwt.verify(token, config.secret, function (err, decoded) {
if (err) {
return res.json({success: false, message: ‘token信息错误.‘});
} else {
console.log(decoded.username);
r.rawCall([‘HEXISTS‘, decoded.username, ‘token‘], function (err, d) {
if (err) throw err;
console.log(d)
if (d === 1) {
req.decoded = decoded;
next();
} else {
return res.status(403).send({
success: false,
message: ‘token已经过期!‘
});
next()
}
})
}
});
} else {
return res.status(403).send({
success: false,
message: ‘没有提供token!‘
});
}
}
代码文件结构
请参考用 nodejs express 搭建 restful api