Recommand · May 19, 2021 0

How to add user in req.body using passport js?

Without passport, I have added simple middleware to authorize user as below.

const jwt = require('jsonwebtoken');

module.exports = (req, res, next) => {
  const authHeader = req.get('Authorization');
  
  const token = authHeader.split(' ')[1];
  let jwttoken;
  try {
    jwttoken = jwt.verify(token, 'secret');
  } catch (err) {
    err.statusCode = 500;
    throw err;
  }
  if (!jwttoken) {
    const error = new Error('Not authenticated.');
    error.statusCode = 401;
    throw error;
  }
  req.userId = jwttoken.userId;
  next();
};

with passport, I have added middleware as below

const options = {
    jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
    secretOrKey: 'SECRET'
}

module.exports = (passport) => {
    passport.use(new Strategy(options, async (payload, done) => {
        await user.findByPk(payload.userId).then(user => {
            if (user) {                    
                return done(null, user);
            }
            return done(null, false);
        }).catch(error => {
            return done(null, error);
        });
    }));
}

Question: like I was adding user to request without passport as req.userId = jwttoken.userId, how can we do it with passport middleware?

At passport this is accomplished with that line of code on your module.exports:

return done(null, user);

This tells passport that the information should be sent to the next function callback at req.user.

So for example, if you "user.findByPk(payload.userId)" response is something like:

{
  "name": <NAME>
  "profile": <profile>
}

At your protected endpoint’s callback, you should see it on req.user.
For example:

app.post('/profile', passport.authenticate('jwt', { session: false }),
    function(req, res) {
        res.send(req.user.profile);
    }
);

With req.user.profile being equal to of the "user.findByPk(payload.userId)" response.