Json Web令牌verify()返回错误的jwt [英] Json Web Token verify() return jwt malformed
问题描述
const jwt = require("jsonwebtoken");
const SECRET = "superSuperSecret";
module.exports = function(req, res, next) {
const token = req.body.token || req.query.token || req.headers[ "x-access-token" ];
if (token) {
return jwt.verify(token, SECRET, function(err, decoded) {
if (err) {
return res.json({
success: false,
message: "Failed to authenticate token.",
});
}
req.user = decoded;
return next();
});
}
return res.unauthorized();
};
我正在使用Postman来测试我的API.我用x-access-token
键和值superSuperSecret
设置了标题.我收到错误{"name":"JsonWebTokenError","message":"jwt malformed","level":"error"}
.我正在使用 https://github.com/FortechRomania/express-mongo-example-project/blob/master/src/middlewares/validateToken.js
I'm using Postman to test my API. I setup the header with a x-access-token
key and the value superSuperSecret
. I got the error {"name":"JsonWebTokenError","message":"jwt malformed","level":"error"}
. I'm using this https://github.com/FortechRomania/express-mongo-example-project/blob/master/src/middlewares/validateToken.js
推荐答案
您不能将任何值作为令牌传递.您需要jwt.sign()
来创建令牌.有关更多信息,请参见 JWT 的文档.
You cannot pass any value as token. You need jwt.sign()
to create a token. Look at the documentation of JWT for more information.
还
对于请求标头名称,只需使用Authorization
而不是x-access-token
.将承载置于令牌之前.
For the request Header name just use Authorization
not x-access-token
. Place Bearer before the Token.
Authorization: Bearer TOKEN_STRING
JWT的每个部分都是base64url编码的值.您可以通过以下方式获取令牌:
Each part of the JWT is a base64url encoded value. You can get your token as:
var token = req.headers.authorization.split(' ')[1];
这篇关于Json Web令牌verify()返回错误的jwt的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!