I can't for the life of me seem to figure out how to debug a passport strategy. Am I just conceptually doing something horribly wrong? I've been banging my head at this for about 10 hours now, and haven't gotten a single bit closer.
This is my first time using passport. In this particular scenario, I'm using passport-jwt. I know that the object keys aren't right, but I'm just trying to trace the path through the server using console.log() so I understand how things work. I'm not even reaching the passport.use( new JwtStrategy(..))
.
I've left out unnecessary code. The connection to my mongodb is fine and my mongoose schema's are fine.
I'm testing using a test route server.get('/fakelogin', ...)
that does a request-promise POST to /api/login
. I've also tried using a curl -X POST
and modifying the post route to url query parameter. I just constantly get an "Unauthorized" error without the passport strategy code console.log ever firing.
var server = express();
server.use(passport.initialize());
let opts = {
jwtFromRequest: ExtractJwt.fromBodyField('token'),
secretOrKey: config.apiKey,
algorithms: [ 'HS256', 'HS384' ],
ignoreExpiration: true
};
passport.use(new JwtStrategy(opts, function( jwt_payload, done ) {
// mongoose users query against JWT content
return done(null, true); // EDIT: test to finish flow
}));
server.use('/api', routes);
server.listen(8000);
let routes = express.Router();
routes.post('/securedroute', passport.authenticate('jwt', { session: false }),
( req, res ) => {
res.send('success');
}
);
routes.get('/testsecure', ( req, res ) => { // EDIT: mock request with JWT
let options = {
method: 'POST',
uri: 'http://localhost:8000/api/authentication/securedroute',
body: {
token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwiZW1haWwiOiJhQGEuY29tIiwiYWRtaW4iOnRydWV9.afjyUmC81heavGBk7l9g7gAF5E6_eZeYSeE7FNmksp8'
},
json: true
};
rp(options)
.then( ( info ) => res.json({ info }) )
.catch( ( err ) => res.json({ err }) );
});
export default routes;
Made a couple edits to the code above to finish the flow.
Totally understand that this is super n00b, but hopefully it'll help a beginner trying to understand auth.
So completely missed the fact that you need to send a JWT in the request. The JWT used in the request needs to use the same secret as what you defined in your passport-jwt strategy opts.secretOrKey. If they don't match, you will get an unauthorized and never reach the passport.use strategy block.
Generated a HMAC http://www.freeformatter.com/hmac-generator.html
Created a test JWT https://jwt.io/#debugger
Greate guide, i eventually found http://jonathanmh.com/express-passport-json-web-token-jwt-authentication-beginners/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With