【发布时间】:2020-02-22 06:15:09
【问题描述】:
花了很多时间来解决这个 JWT 错误,终于找到了导致它的原因,但我不明白为什么。
当用户登录时,我的 user.js 文件(模型和路由)会生成一个令牌。
router.post('/login', async (req, res) => {
try {
console.log(req.body.email);
console.log(req.body.password);
const { email, password } = req.body;
const user = await User.findByCredentials(email, password)
if (!user) {
return res.status(401).send({error: 'Login failed! Check authentication credentials'})
}
const token = await user.generateAuthToken()
res.send({ user, token })
} catch (error) {
console.log(error)
res.status(400).send(error)
}
})
userSchema.methods.generateAuthToken = async function() {
// Generate an auth token for the user
const user = this
const token = jwt.sign({
email: user.email,
_id: user._id
},
'badabaloozagoodoo',
{
expiresIn:'1h'
}
)
console.log('Generating token')
console.log(token)
user.tokens = user.tokens.concat({token})
await user.save()
return token
}
它输出一个像这样的令牌:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImpzbWl0aEBnbWFpbC5jb20iLCJfaWQiOiI1ZGIyNGRmYzc5NzUyZTYxOGI3OTk1NDYiLCJpYXQiOjE1NzIwMzkxOTcsImV4cCI6MTU3MjA0Mjc5N30.ctdg8vkne1gvD3-Lo6j-T5BQEMVKBoKBsDGddtuQBUE P>
然后,在后续调用不同路由时,以下中间件会检查令牌以确保用户已获得授权。它不断抛出 JsonWebTokenError: invalid token 错误,我不明白为什么。然后我将请求标头中的令牌打印到字符串中,并注意到由于某种原因它具有 JWT 前缀。
JWTeyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImpzbWl0aEBnbWFpbC5jb20iLCJfaWQiOiI1ZGIyNGRmYzc5NzUyZTYxOGI3OTk1NDYiLCJpYXQiOjE1NzIwMzkxOTcsImV4cCI6MTU3MjA0Mjc5N30.ctdg8vkne1gvD3-Lo6j-T5BQEMVKBoKBsDGddtuQBUE P>
所以,我添加了 coded 以删除 JWT 前缀,现在代码运行没有任何错误。有人可以帮助我了解发生了什么吗?
const jwt = require('jsonwebtoken')
const User = require('../../models/user')
const checkAuth = async(req, res, next) => {
console.log("Check auth")
try {
console.log(req.header('Authorization'))
var token = req.header('Authorization').replace('Bearer ', '')
token = token.replace('JWT', '')
console.log(token)
const data = jwt.verify(token, 'badabaloozagoodoo')
const user = await User.findOne({ _id: data._id, 'tokens.token': token })
if (!user) {
throw new Error('User not found')
}
req.user = user
req.token = token
next()
} catch (error) {
console.log('Auth failed')
console.log(error)
res.status(401).send({ error: 'Not authorized to access this resource.' })
}
}
module.exports = checkAuth
【问题讨论】: