Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply one Guard to multiple routes in Nestjs

Tags:

nestjs

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

like image 412
Yamid Granda Avatar asked Dec 03 '22 20:12

Yamid Granda


1 Answers

You have three possible solutions to set guard:

  • apply to method (your example)
  • apply to controller
  • apply globally

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

like image 184
Vladyslav Moisieienkov Avatar answered Jan 27 '23 02:01

Vladyslav Moisieienkov