Set a custom request property after successful authentication in passport

501 Views Asked by At

I am looking to create a custom property on the request as early in the request lifecyle as possible, the use case for this is so that I can store the users profile (fetched from the DB) and store this in the request so that in my controller methods I can access it easily without having to inject the ProfileService and fetching it in the controller.

I am hoping to just fetch it from the Req() req instead. (i.e. req.profile.

I thought that an option would be to set this property in my JWT Strategy:

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      passReqToCallback: true,
      secretOrKeyProvider: passportJwtSecret({
        cache: true,
        rateLimit: true,
        jwksRequestsPerMinute: 5,
        jwksUri: `https://${process.env.AUTH0_DOMAIN}/.well-known/jwks.json`,
      }),

      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      audience: `https://${process.env.AUTH0_AUDIENCE}`,
      issuer: `https://${process.env.AUTH0_DOMAIN}/`,
    });
  }

  validate(request: Request, payload: JwtPayload) {
    // SET A CUSTOM REQUEST PROPERTY HERE FOR PROFILE

    return payload;
  }
}

I guess I have two questions:

  1. Is this the right way? Any pros/cons to this?
  2. How to save a custom property on the request object for use later on? I've attempted request.profile = 'test' but this throws errors?
1

There are 1 best solutions below

0
Jay McDoniel On

Express's Request doesn't have a profile property, nor does it have a general [index: string]: any type so that you can tack on whatever you want. To get around this, you can create a custom type that extends the Request type with the properties you need.

export interface RequestWithProfile extends Request {
  profile: ProfileType
}