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

330
Visualizações
Apply JWT Guard for an endpoint but do not apply it when it has a request parameter

Is there a way to use if conditions when applying @UseGuards(JwtAuthGuard) rule for an endpoint in controller?

@UseGuards(JwtAuthGuard)
@Get("/foo/:bar?")
async get(@Param() param: RequestParamDto)

Having an endpoint /foo should require JWT Authorization token when calling it (which it does with the code above), but when we are passing something in a request parameter e.g. /foo/bar it should turn off a guard.

I don't see a way to apply if-else conditions when applying Guards on a Controller level.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can apply if-else conditions in guards. Not at the controller level though, but you can achieve your desired condition following the next steps:

First of all, define a new decorator with the following code:

import { SetMetadata } from '@nestjs/common';
export const IS_PUBLIC_KEY = 'isPublic';
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);

With this code, you are going to define a new decorator by the name @Public(). And link the IS_PUBLIC_KEY to the value true which in turn will be linked to the decorator. The purpose of its existence is to enable the guard to identify which routes do you desire to be accessed by everyone.

The next step would be to add the decorator to the desired route:

@UseGuards(JwtAuthGuard)
@Get("/foo/:bar")
@Public()
async get(@Param() param: RequestParamDto)

Finally, in the JwtAuthGuard class you should have the following code:

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

  canActivate(context: ExecutionContext) {
    const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);
    if (isPublic) {
      return true;
    }
    return super.canActivate(context);
  }
}

In the code inside the canActivate function, you are now using the reflector property of NestJs to fetch the constant IS_PUBLIC_KEY added to the custom decorator. Thus, the guard will be able to tell when you want the route to be public for everyone to access.

If you want further information on this issue, refer to the official documentation here.

about 4 years ago · Juan Pablo Isaza 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