首页 > 解决方案 > 使用 JWT Nodejs 总是返回 401 Unauthorized

问题描述

我正在尝试使用 jwt 身份验证策略对 nodejs api 进行身份验证,但它总是抛出 401 未经授权的错误。我尝试了各种实现,但 jwt 验证功能似乎不起作用。

const expressJwt = require('express-jwt');

function authJwt() {
    const secret = process.env.secret;
    const api = process.env.API_URL;
    return expressJwt({
        secret,
        algorithms: ['HS256'],
        isRevoked: isRevoked
    }).unless({
        path: [
            {url: /\/api\/v1\/products(.*)/ , methods: ['GET', 'OPTIONS'] },
            {url: /\/api\/v1\/categories(.*)/ , methods: ['GET', 'OPTIONS'] },
            `${api}/users/login`,
            `${api}/users/register`,
        ]
    })
}

async function isRevoked(req, payload, done) {
    if(!payload.isAdmin) {
        done(null, true)
    }

    done();
}



module.exports = authJwt

标签: node.jsjwt

解决方案


推荐阅读