Reputation: 21
I'm trying to make a very simple authentication scenario with passport-jwt. When I access a protected path, it keeps returning 'unauthorized'. I've tried almost everything suggested on similar threads but it doesn't work. All I want to do for now is have a call to 'authenticate' path in order the JWT token to be generated and then call the 'protected' path and allow access. For simplicity, I have all the code in server.js.
Here is the code:
const express = require("express");
const passport = require('passport');
const jwt = require('jsonwebtoken');
const JWTStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const secret = "s0m3$3Cret$h0lyC0d3&$";
const options = {
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken,
secretOrKey: secret,
algorithms: ['RS256']
};
passport.use(new JWTStrategy(options, function(jwt_payload, done){
return done(null, {id: 'FAKE_ID'});
}
));
const app = new express();
app.get('/authenticate', (req, res, next) => {
const token = jwt.sign({sub:'FAKE_ID'},secret,{expiresIn: 604800});
res.status(200).json({ success: true, message: 'Logged in successfully!', token: 'Bearer ' + token});
})
app.get('/protected', passport.authenticate('jwt', { session: false }), (req, res, next) => {
res.status(200).json({ success: true, msg: "You are successfully authenticated to this route!"});
});
app.listen(3000, () => {
console.log('App running at 3000')
})
Thank you in advance
Upvotes: 0
Views: 196