【问题标题】:Apply one Guard to multiple routes in Nestjs在 Nestjs 中将一个 Guard 应用于多个路由
【发布时间】:2018-11-08 18:36:48
【问题描述】:

例如:将一个中间件应用于我们可以使用的多个路由:

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 },
        );
    }
}

我想将 AuthGuard 应用于多条路线,¿ 最佳做法是什么?谢谢...

目前我在这样的控制器函数中使用一个一个的装饰器,

@Get()
@UseGuards(AuthGuard('jwt'))
async findAll(@Request() request): Promise<User[]> {
      return await this.usersService.findAll();
}

但我正在寻找一个大规模的实现

【问题讨论】:

  • 你用的是什么版本的 NestJS?
  • 核心版本 5.0.0-beta.6
  • 另外稳定版5.0.0已经发布了,所以我觉得最好切换一下,而且package.json里只有几行)

标签: nestjs


【解决方案1】:

您有三种可能的解决方案来设置守卫:

  • 应用于方法(您的示例)
  • 适用于控制器
  • 全球应用

应用于控制器:

@Controller('cats')
@UseGuards(RolesGuard)
export class CatsController {}

全局应用防护:

const app = await NestFactory.create(ApplicationModule);
app.useGlobalGuards(new RolesGuard());

Guards 文档中的所有示例 - https://docs.nestjs.com/guards

【讨论】:

  • 感谢 Vladyslav,您的回答非常有用。
  • 它有办法为特定控制器应用全局防护并将其删除
猜你喜欢
  • 2019-03-16
  • 1970-01-01
  • 1970-01-01
  • 2019-06-02
  • 2021-04-19
  • 1970-01-01
  • 1970-01-01
  • 2019-10-01
  • 2021-08-06
相关资源
最近更新 更多