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

336
Vistas
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 Respuestas
Responde la pregunta

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 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