【发布时间】:2018-12-29 14:35:59
【问题描述】:
我目前正在尝试使用 express、node 和 MongoDB 构建一个 REST API。现在进行身份验证,我使用的是 JWT。
这是检查 JWT 令牌的代码
const token = req.headers['authorization'];
if (token){
const tokens = token.split(' ');
const key = tokens[1];
jwt.verify(key, config.jwtKey, (err, authData) => {
if (err){
res.status(403).json({
success: false,
message: "Authentication2 failed"
});
}
// User authenticated
// Do something
next();
});
} else {
res.status(403).json({
success: false,
message: "Authentication failed"
});
}
现在,这段代码运行良好。
为了制作 JWT,这里是代码
........
........
const token = jwt.sign(
{
email: user[0]._email,
userId: user[0]._id
}, config.jwtKey,{ expiresIn: "1d" });
........
........
现在我的问题是我是否也应该通过检查数据库中用户信息的存在来验证用户以使其更安全?
例如,在我的数据库中搜索email 和userId。
我在这个项目中使用 node、express、MongoDB、Mongoose 和 JWT。
【问题讨论】:
标签: node.js mongodb authentication jwt