For example: to apply one middleware to multiple routes we can use:
export class UserModule {
public configure(consumer: MiddlewaresConsumer) {
consumer.apply(AuthMiddleware).forRoutes(
{ path: '/users', method: RequestMethod.GET },
{ path: '/users/:id', method: RequestMethod.GET },
{ path: '/users/:id', method: RequestMethod.PUT },
{ path: '/users/:id', method: RequestMethod.DELETE },
);
}
}
I would like apply AuthGuard to multiple routes, ¿ what is the best practice ? thanks ...
Currenly I use one by one decorator inside controller function like this,
@Get()
@UseGuards(AuthGuard('jwt'))
async findAll(@Request() request): Promise<User[]> {
return await this.usersService.findAll();
}
but I'm looking for a masive implementation
You have three possible solutions to set guard:
Apply to controller:
@Controller('cats')
@UseGuards(RolesGuard)
export class CatsController {}
Apply guard globally:
const app = await NestFactory.create(ApplicationModule);
app.useGlobalGuards(new RolesGuard());
All examples from guards docs - https://docs.nestjs.com/guards
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With