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