Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

282
Vistas
Access request body/header variables within jwt strategy - nest js

How can I access headers variables/body in a strategy?

Currently, the JWT looks like this:

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(
    private readonly appConfigService: AppConfigService,
    private readonly usersService: UsersService
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: appConfigService.configs.JWT_SECRET_KEY
    });
  }

  async validate(payload: { id: string }) {
    const user = await this.usersService.findBusinessUserById(
      'BUSINESS_ID', // TODO: replace this with business id from the request
      payload.id
    );

    if (user) {
      return user;
    }

    return null;
  }
}

and the guard looks like this:

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  constructor(private readonly reflector: Reflector) {
    super();
  }

  canActivate(
    context: ExecutionContext
  ): boolean | Promise<boolean> | Observable<boolean> {
    const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
      context.getHandler(),
      context.getClass()
    ]);

    return isPublic ? true : super.canActivate(context);
  }

  getRequest(context: ExecutionContext) {
    const ctx = GqlExecutionContext.create(context);
    const req = ctx.getContext().req;

    return req;
  }
}

If I try to return anything but the request from the guards I get the following

TypeError: Cannot read properties of undefined (reading 'authorization')
    at JwtStrategy._jwtFromRequest

Is there a way to get the request body or variables from the header in the strategy?

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Answer found here https://stackoverflow.com/a/68180268/6226852. In order to access the request in the validate method, I needed to pass passReqToCallback and set its value to true when calling super inside the constructor.

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda