node.js - Json Web Token verify() 返回 jwt 格式错误

标签 node.js express jwt postman

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 设置 header 。我收到错误 {"name":"JsonWebTokenError","message":"jwt malformed","level":"error"}。我正在使用这个 https://github.com/FortechRomania/express-mongo-example-project/blob/master/src/middlewares/validateToken.js

最佳答案

您不能将任何值作为标记传递。您需要 jwt.sign() 来创建 token 。查看 JWT 的文档获取更多信息。

此外,

对于请求 header 名称,只需使用 Authorization 而不是 x-access-token。将 Bearer 放在 Token 之前。

Authorization: Bearer TOKEN_STRING

JWT 的每个部分都是一个 base64url 编码值。您可以获得您的 token :

var token = req.headers.authorization.split(' ')[1];

关于node.js - Json Web Token verify() 返回 jwt 格式错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51849010/

相关文章:

node.js - Nodejs 提供 1 个 api 端点和一个 html 页面

node.js - NodeJS-Mongo : Querying the database and gridfs and returning both the document and the image to the user

javascript - 设置cookie跨原点

android - Google Play 服务返回使用非 Google key 签名的 token

security - 如何保护 webhook 身份

Envoy 验证失败

Node.js - Azure - Socket.io - 为什么我用完了并发套接字?

node.js - 启动 Node 服务器并使其保持运行

node.js - Node.js 如何处理非阻塞 IO,即使它是单线程的?

angularjs - 未设置 Node.js 响应 header