Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

278
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda