javascript - 响应 header 中未设置 JWT token

标签 javascript node.js express jwt

我有以下函数,它通过创建响应 header 来对用户进行身份验证:

function authenticateUser(res, id) {
    const payload = {
        id
    }
    const token = jwt.sign(payload, config.JWT_KEY, {
        expiresIn: '24h'
    })
    res.set('authorization', token)
    res.redirect('/user/profile')
    res.end()
}

但是,当我重定向到/user/profile 时,它​​会输出授权 header 未定义:

controller.checkAuthorizaion = (req, res, next) => {
    const token = getJWTToken(req)
    console.log(token);
    if(!token) 
        Router.redirect(res, '/', 401)
    else {
        jwt.verify(token, config.JWT_KEY, (err, data) => {
            if(err)
                Router.redirect(res, '/', 401)
            else  {
                res.userId = data.id
                next()
            }
        })
    }
}

为什么不工作?如何将我的 jwt token 发送回客户端?我以为 jwt.sign() 会自动发送它。

最佳答案

如果您使用jsonwebtoken,那么您需要将其作为async函数调用或提供回调:

async function authenticateUser(res, id) {
    const payload = {
        id
    }
    const token = await jwt.sign(payload, config.JWT_KEY, {
        expiresIn: '24h'
    })
    res.set('authorization', token)
    res.redirect('/user/profile')
    res.end()
}

getJWTToken(req) 也应该被称为 async 之一:

controller.checkAuthorizaion = async (req, res, next) => {
    const token = await getJWTToken(req)
    console.log(token);

当然,在 getJWTToken 内部:您也应该将 jwt.verify 作为异步函数调用。

关于javascript - 响应 header 中未设置 JWT token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73193460/

相关文章:

javascript - 如何使用 Thinktecture.IdentityServer.v2 和 Node.js 来实现 WS-Federation?

javascript - 如何在 Node.js 中正确取消 http 请求?

node.js - Expressjs 应用程序,使用 websockets 进行聊天。为 websocket 服务器使用不同的端口?

javascript - 基本的 node.js 代码不工作

node.js - 如何获取带有父子关系的json结果?(查看详情)

javascript - 意外的标记 'case'(switch 语句)

javascript - Discord.js 翻译 bot for Discord

backbone.js - 在新窗口中打开主干 View

javascript - 将 base64 编码的图像上传到 Node.js 服务器不起作用

javascript - 从 Javascript 数组中删除空数组