Search code examples
javascriptnode.jsauthenticationpassport.jspassport-jwt

Access jwtFromRequest from callback


I'm learning passport.js with JWT strategy and I want to create a system to logout users.

I want to process like that:

  1. When a user logs out, his token is stored in my database, in a table called InvalidTokens
  2. Each time a user makes a protected request, I want to check if his token is in the table InvalidTokens or not

The thing is that I don't know how to access the field jwtFromRequest in the code below:

// passport.js
// File where I store my authentication strategies

// ...

/**
 * Use JWT strategy for all the other requests that need authentication on the
 * server 
 */
var opts = {
  jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken(),
  secretOrKey: 'secret',
}

passport.use('jwt', new JWTStrategy(
  opts,
  async (jwtPayload, done) => {
    try {
      const token = await TokenInvalide.findOne({
        where: {
          Token: '<token_value_I_can\'t_reach>',
        }
      })

      if (token !== null)
        return done(null, false);

      return done(null, jwtPayload.idUtilisateur);

    } catch (e) {
      console.log(e);
      return done(null, false);
    }
  }
));

Solution

  • According to the doc you can pass the request object to the call back by setting the passReqToCallback to true

    Haven't tested this but should be the right direction

    var opts = {
      jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken(),
      secretOrKey: 'secret',
    
      passReqToCallback: true // <----- Add this
    
    }
    
    passport.use('jwt', new JWTStrategy(
      opts,
      async (req, jwtPayload, done) => {
    
        const rawJWTToken = req['Authorization'].split(' ')[1]
    
        ...
      }
    ));