Reputation: 11
Spent a lot of time banging on this JWT error and finally discovered what was causing it, but I don't understand why.
My user.js files (model and routes) generate a token when a user logs in.
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
}
It outputs a token like this:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImpzbWl0aEBnbWFpbC5jb20iLCJfaWQiOiI1ZGIyNGRmYzc5NzUyZTYxOGI3OTk1NDYiLCJpYXQiOjE1NzIwMzkxOTcsImV4cCI6MTU3MjA0Mjc5N30.ctdg8vkne1gvD3-Lo6j-T5BQEMVKBoKBsDGddtuQBUE
Then, on a subsequent call for a different route, the following middleware checks to token to make sure the user is authorized. It kept throwing a JsonWebTokenError: invalid token error and I couldn't understand why. Then I printed the token from the request header to string and noticed that it had a JWT prefix for some reason.
JWTeyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImpzbWl0aEBnbWFpbC5jb20iLCJfaWQiOiI1ZGIyNGRmYzc5NzUyZTYxOGI3OTk1NDYiLCJpYXQiOjE1NzIwMzkxOTcsImV4cCI6MTU3MjA0Mjc5N30.ctdg8vkne1gvD3-Lo6j-T5BQEMVKBoKBsDGddtuQBUE
So, I added coded to remove the JWT prefix and now the code runs without any error. Could someone help me understand what is going on?
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
Upvotes: 0
Views: 2755
Reputation: 11
Well. I found my error. I had set up an interceptor to verify the token and it was adding the 'JWT' prefix
req = req.clone({headers:req.headers.set('Authorization', 'JWT'+token)}); //passing request
return next.handle(req)
Upvotes: 1