Node.js JWT nodejs/express-签名无效
我遇到了Jwt的问题,尤其是一个错误“无效签名” 我在用户登录后生成一个令牌(jsonwebtoken) 然后我创建了一个express jwt中间件,将其添加到routes:Node.js JWT nodejs/express-签名无效,node.js,angular,express,jwt,Node.js,Angular,Express,Jwt,我遇到了Jwt的问题,尤其是一个错误“无效签名” 我在用户登录后生成一个令牌(jsonwebtoken) 然后我创建了一个express jwt中间件,将其添加到routes: var auth = jwt({ secret: process.env.SRCT, userProperty: 'payload' }); 这样使用: router.get('/', auth, ctrlUser.slash); 根据调试器,我创建的JWT在前端请求(授权承载)中传递,与登录后创建的JWT相
var auth = jwt({
secret: process.env.SRCT,
userProperty: 'payload'
});
这样使用:
router.get('/', auth, ctrlUser.slash);
根据调试器,我创建的JWT在前端请求(授权承载)中传递,与登录后创建的JWT相同
但不幸的是,在对nodejs后端的每个请求之后,我仍然有错误{“message”:“UnauthorizedError:invalid signature”}
有人能告诉我我有一个无效的签名有什么不对吗
提前感谢您的验证功能在哪里?您需要检查向受保护区域发出的每个请求是否真的有效,jwt提供了一个函数verify来执行此操作。您似乎没有解析令牌的请求头,也没有为此使用jwt库的
verify()
函数。您的auth中间件应该如下所示
module.exports = (req, res, next) => {
try {
//parse the token from Authorization header (value of "bearer <token>")
let token = req.headers.authorization.split(" ")[1];
//verify the token against your secret key to parse the payload
const tokenData = jwt.verify(token, process.env.JWT_SECRET_KEY);
//add the data to the request body if you wish
req.user = tokenData;
next();
} catch (err) {
res.status(401).json({
message: "Unauthorized access error!",
});
}
};
module.exports=(请求、恢复、下一步)=>{
试一试{
//从授权头解析令牌(值为“bearer”)
let token=req.headers.authorization.split(“”[1];
//根据您的密钥验证令牌以解析有效负载
const tokenData=jwt.verify(token,process.env.jwt\u SECRET\u KEY);
//如果愿意,请将数据添加到请求正文中
req.user=令牌数据;
next();
}捕捉(错误){
res.status(401).json({
消息:“未经授权的访问错误!”,
});
}
};
module.exports = (req, res, next) => {
try {
//parse the token from Authorization header (value of "bearer <token>")
let token = req.headers.authorization.split(" ")[1];
//verify the token against your secret key to parse the payload
const tokenData = jwt.verify(token, process.env.JWT_SECRET_KEY);
//add the data to the request body if you wish
req.user = tokenData;
next();
} catch (err) {
res.status(401).json({
message: "Unauthorized access error!",
});
}
};