Reputation: 59
I am experiencing a problem with passport jwt.
Whenever i send a GET request adding authorization as Bearer <generated-token>
in the header to the /profile route, i get a response which says "unauthorized". Here's a sample of what's happening:
https://ibb.co/qmYmfJs
Any idea what might be causing this issue?
The packages I am using are:
"cors": "2.8.5",
"dotenv": "16.0.3",
"express": "4.18.2",
"jsonwebtoken": "9.0.0",
"mongoose": "7.0.4",
"nodemon": "2.0.22",
"passport": "0.6.0",
"passport-jwt": "4.0.1"
I have this code on server/config/passport.js:
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = process.env.SECRET_KEY;
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
User.findOne({ _id: jwt_payload.sub })
.then(user => {
if (user) {
return done(null, user);
} else {
return done(null, false);
}
})
.catch(err => {
return done(err, false);
});
}));
This on server/app.js
//login route
app.post("/login", async (req,res) =>{
const user = await User.findOne({phone : req.body.phone});
if(!user){
res.status(400).send("User not found!");
}
if(!bcrypt.compareSync(req.body.password, user.password)){
res.status(400).send("Incorrect password!");
}
const payload = {
id: user._id,
phone: user.phone
}
const token = jwt.sign(payload, process.env.SECRET_KEY, {expiresIn: "2d"});
return res.status(200).send({ success : true, message : "Log in successful", token : "Bearer "+token});
})
//profile route
app.get('/profile', passport.authenticate('jwt', { session: false }),
function(req, res) {
res.status(200).send({
message: "Tomar account",
token: "Bearer "+token,
user: {
id: req.user._id,
phone: req.user.phone
}
});
}
);
I am using thunderclient for testing the API endpoints. I have tried other ExtractJwt methods that does not use bearer tokens, such as ExtractJwt.fromAuthHeaderWithScheme('jwt')
but that doesn't work also.
Upvotes: 1
Views: 66