花了很多时间解决这个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
然后,在随后的对另一条路由的调用中,以下中间件检查令牌以确保用户被授权。它不断抛出 JsonWebTokenError:无效令牌错误,我不明白为什么。然后,我将令牌从请求标头打印到字符串中,并注意到出于某种原因它具有 JWT 前缀。
JWTeyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImpzbWl0aEBnbWFpbC5jb20iLCJfaWQiOiI1ZGIyNGRmYzc5NzUyZTYxOGI3OTk1NDYiLCJpYXQiOjE1NzIwMzkxOTcsImV4cCI6MTU3MjA0Mjc5N30.ctdg8vkne1gvD3-Lo6j-T5BQEMVKBoKBsDGddtuQBUE
因此,我添加了删除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
答案 0 :(得分:0)
好吧。我发现了我的错误。我已经设置了一个拦截器来验证令牌,并且正在添加“ JWT”前缀
req = req.clone({headers:req.headers.set('Authorization', 'JWT'+token)}); //passing request
return next.handle(req)