Json Web Token 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
.将 Bearer 放在 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 Token verify() 返回 jwt 格式错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!