Passport Jwt 401 Unauthorized Error

Saheed Adedeji
2 min readMar 30, 2020

--

I’m writing this after spending the whole day trying to figure out how to get the user details of an authenticated user using the req.user method.

I used Passport JWT strategy my project. It has been working fine, i’m done with the register endpoint and all that but whenever i hit a protected
endpoint i get the error “401 Unauthorized” even though i included the token gotten from the register endpoint in the authorization area of the
header.

I think the main problem was from registeration, though the endpoint was working but after regisering a user, i’m sendng some objects back which
include the token created, username, email and others. This worked fine but it was the beginning of my issue.

The tutorial i was watching got the token using the jwt.sign method with

const token = jwt.sign(user, config.secret, {expiresIn: 604800}); // Expires in 1 week

I tried using this and got the error “Expected ‘payload’ to be a plain text.”, while trying to resolve this i checked the passportjs documentation
and was able to resolved this with

const token = jwt.sign({ exp: 604800, data: user }, config.secret); // Expires in 1 week

Unknown to me those two different parameters will generate different token even though i’m using the same secret key and expiration period. It’s
kind of hard to know that just from seeing the token cause it’s kind of pretty long.

So the way i fixed this is by using the jwt method with the following parameters:

const token = jwt.sign(user.toJSON(), config.secret, {expiresIn: 604800}); // Expires in 1 week

This is showing that you have to convert the user to JSON before passing it as a payload into the jwt sign function in the registeration endpoint.

It’s also worth mentioning that the secret key used here should be the same as the secret key used in the passport.js where you setup your passport
authentication. And you should also concatentane “JWT “ to the token while sending it so you should have this as your response after registeration

res.json({
success: “true”,
token: “JWT “ + token,
user: {
id: user._id,
name: user.name,
username: user.username,
email: user.email
}
});

Also here is what i have for my passport.js configuration

module.exports = passport => {
let opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme(“JWT”);
opts.secretOrKey = config.secret;
passport.use(
new JwtStrategy(opts, (jwt_payload, done) => {
// console.log(jwt_payload._id);
User.findOne({ id: jwt_payload.sub }, (err, user) => {
if (err) {
return done(err, false);
}
if (user) {
return done(null, user);
} else {
return done(null, false);
}
});
})
);

This is my first post so i’m sorry if it feels too long or not informative enough but i hope it helps you save time. Thanks.

--

--