Today I Learned

Accessing request in the validate of JWT strategy

The default definition for the JwtStrategy offers to pass the payload parameter to the validate function:

import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { jwtConstants } from './constants';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: jwtConstants.secret,
    });
  }

  async validate(payload: any) {
    return { userId: payload.sub, username: payload.username };
  }
}

There are sometimes cases where the validate fn should receive the request object. To have this possibility, specify the passReqToCallback to true:

    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: jwtConstants.secret,
      passReqToCallback: true // <-----
    });

In that way, the validate function will firstly receive request and secondly jwtPayload:

  async validate(request: Request, payload: any) {
    // do something with the request
    return { userId: payload.sub, username: payload.username };
  }