【问题标题】:Exclude endpoints when using 'useGlobalGuards' on NestJS在 NestJS 上使用“useGlobalGuards”时排除端点
【发布时间】:2021-09-17 11:08:54
【问题描述】:

我刚开始在我的 main.ts 文件中使用useGlobalGuards 方法:

[...]
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe({
    transform: true,
  }))
  app.useGlobalGuards(new AuthGuard)
[...]

因此,所有端点都在使用我的 AuthGuard,如果请求标头上没有有效的身份验证令牌,则会引发 401 错误...在此之前,我在每个端点上都使用 @UseGuards(AuthGuard)类,所以如果我想创建一个公共 api(比如用户创建),我只需要删除这个装饰器。

是否可以使用useGlobalGuards 并且仍然只有少数不需要身份验证令牌的公共 API? (useGlobalPipes 方法的问题相同)

【问题讨论】:

    标签: javascript node.js typescript nestjs class-validator


    【解决方案1】:

    This is a common use case described in the docs.

    本质上,您需要为端点创建某种元数据,这些元数据将允许使用@SetMetadata() 或自定义装饰器公开使用,并在防护中读取该元数据。如果元数据存在,则应将其视为公共路由并跳过身份验证。

    【讨论】:

      猜你喜欢
      • 2021-03-06
      • 2021-12-10
      • 1970-01-01
      • 2021-05-30
      • 1970-01-01
      • 2020-04-16
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多