I'm using the following code to create a JWT web-token:
function generateToken(req, user) {
const ONE_WEEK = 60 * 60 * 24 * 7
return jwt.sign(user, config.auth.jwtExtraSecret, {
expiresIn: ONE_WEEK
}) // secret is defined in the environment variable JWT_SECRET
}
Then when it comes to send data to the client i do the following code
res.send({
user: sendData(user, 'username','tokens','_id', 'extraToken'),
extraToken: generateToken(req, userJson),
})
Note: that extraToken is not attached directly to the user model, and i dont want it to be attached there. There is another token that is assigned to the user model (permanent token) and it works good when authenticating routes. (so please restrain yourself from giving advice on that)
The purpose of the extraToken is to have an expiration date.
For passport strategy
let options = {
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: config.auth.jwtExtraSecret
}
passport.use(
new JwtStrategy(options, async function (jwtPayload, done) {
try {
const user = await User.findOne({_id: jwtPayload._id})
if (!user) {
return done(new Error(), false)
}
return done(null, user)
} catch (err) {
console.log('error here in catch')
return done(new Error(), false)
}
})
)
For assessing
jwtAuthCheck(req, res, next) {
passport.authenticate('jwt', function (error, user) {
if (error || !user) {
res.status(403).send({
message: 'you dont have an access'
})
} else {
req.user = user
next();
}
})(req, res, next)
},
When sending request to the route in my header
as a key i have "Authorization" and as a value ~Bearer ${token}~
THE PROBLEM and THE QUESTION
By some reason it keeps giving me a message
"message": "you dont have an access"
The error begins in a catch statement in passport.use, not sure what i'm doing wrong. Please help, have been on this problem for very long