我有以下函数,它通过创建响应 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/