passport
passport copied to clipboard
Display warning when strategies aren't supplied with the right information
I was having problems using a JWT strategy - I set it up and it looked just like my Local strategy, but it wasn't running.
const jwtOptions = {
jwtFromRequest: ExtractJwt.fromAuthHeader(),
secretOrKey: config.auth.passport.key,
};
const jwtLogin = new JwtStrategy(jwtOptions, (payload, done) => {
console.log('Using JWT Strategy');
console.log(payload);
User.findById(payload._id, (err, user) => {
if (err) {
return done(err, false);
}
if (user) {
done(null, user);
} else {
done(null, false);
}
});
});
passport.use(jwtLogin);
It looks fine, but it would never run - I'd never see 'Using JWT Strategy' in my console. After a while of digging around, I found that Passport doesn't run the verification callback if it doesn't have the proper information. My mistake is that, after a successful login (using the Local strategy), I was sending the JWT token without a space, like so:
res.status(200).json({
token: `JWT${generateToken(userInfo)}`,
user: userInfo,
});
I solved my problem by putting a space after JWT:
res.status(200).json({
token: `JWT ${generateToken(userInfo)}`,
user: userInfo,
});
And now everything is working as expected. But, it was a very roundabout procedure to debug this. It would be great if there was some kind of warning provided when a strategy is not going to be used because the necessary arguments aren't being provided.
(A few more details here, in case others who have this problem find this issue: https://stackoverflow.com/questions/43091021/getting-401-unauthorized-status-while-authorizing-jwt-token-using-passport-jwt/45272000#45272000)