Saturday 11 March 2017

Passing the JWT payload down to the express route handlers

I am willing to use JWT for my Node.js Express-based web application, and I plan to use passport-jwt to handle the user authentication and persistence.

I am somewhat new to the Passport.js and passport-jwt, so perhaps I am missing something obvious here, but I fail to see what is the suggested way how to pass the JWT payload object down to the route handlers that need to access the data stored there.

The examples of Passport.js typically show that one has to create a strategy that features the verify callback whose purpose is to find the user object and call the done(null, user), if such user can be found. This user object then is stored in req.user property that lets the route handlers to access it.

But I plan to store more information in my JWT, not just the user id: things like session state, id, ip address, etc. I need the route handlers to be able to access this other data, too, not just the identified user object.

Currently I am solving this by using a very trivial verify callback that passes the whole JWT payload object instead of just user:

const passportJWT = require("passport-jwt");
const JwtStrategy = passportJWT.Strategy;
var strategy = new JwtStrategy(jwtOptions, function(jwt_payload, next) {
  console.log('JWT payload received:', jwt_payload);
  // Skipping the user object identification here
  next(null, jwt_payload);
});

This lets me access the whole payload object from the route handlers via req.user, but it feels kind of wrong, because the req.user perhaps really should be used just for the user object.

So, what is the Passport.js-correct way to pass down extra data that can be then accessed from the route handlers down the road?



via Passiday

No comments:

Post a Comment