【问题标题】:In NestJS, what is the decorator I can add at a controller level to add an Authorization header to my Swagger docs?在 NestJS 中,我可以在控制器级别添加什么装饰器以向我的 Swagger 文档添加授权标头?
【发布时间】:2021-08-29 08:06:57
【问题描述】:

我正在使用 NestJS 7.6.11。我的控制器上有以下装饰器...

@Controller('private')
@ApiTags('MyObjects')
@ApiConsumes('application/json')
@ApiProduces('application/json')
@UseInterceptors(new JwtInterceptor())
export class MyController {

我是否可以添加任何装饰器来生成 Swagger (OpenAPI 3) 文档,从而表明我的控制器中的所有方法都需要具有“授权”标头?

编辑:作为回应,我添加了@ApiHeader,所以我的控制器和方法看起来像

@

Controller('myendpoint')
@ApiTags('MyObject')
@ApiConsumes('application/json')
@ApiProduces('application/json')
@ApiHeader({
  name: 'authorization',
  description: 'Auth token',
})
@UseInterceptors(new JwtInterceptor())
export class MyObjectController {

...
 @Get('/:id')
  @ApiOkResponse({
    description: 'OK',
    type: Content,
  })
  @ApiBadRequestResponse()
  @ApiInternalServerErrorResponse()
  @ApiOperation({
    summary: 'Get object by id',
    description: 'Get object by id',
    operationId: 'findObjectById',
  }) 
  findObjectById(@Req() req, @Param('id') id: string): Promise<MyObject> {

但是当生成 swagger 文档时,虽然我可以输入“授权”标头值,

当我单击“执行”时,它不会包含在我的 curl 中,它生成为

curl -X GET "http://localhost:8060/myendpoint/abcdef" -H  "accept: application/json"

【问题讨论】:

    标签: swagger nestjs openapi authorization-header


    【解决方案1】:

    @ApiHeader()@ApiBasicAuth()@ApiBearerAuth()@ApiOAuth2()@ApiSecurity(),所有这些都可以在this page上找到。您的具体情况可能会有所不同,但其中一种应该可以解决问题。

    【讨论】:

    • 我尝试了 ApiHeader,因为我希望将其应用于我的控制器中的所有方法,但 Swagger 在从 Swagger UI 发送请求时没有添加该标头。我认为这可能与此有关——github.com/nestjs/swagger/issues/486。还有其他方法吗?
    • 看起来该问题已在 @nestjs/swagger@4.1.1 中修复。
    • 嗯,我使用的是 4.7.12 版本。我应该恢复到旧版本吗?
    • 不,在控制器上使用@ApiHeader() 应该还是可以的。
    • 在 OpenAPI 3 中,Authorization 标头必须定义为 安全方案,因此 @ApiHeader() 将不起作用 - Swagger UI 将 ignore 标头参数命名为 @987654334 @(根据规范)。如果您的身份验证令牌具有“Bearer”前缀,请使用ApiBearerAuth()。否则请尝试使用@ApiSecurity + DocumentBuilder().addApiKey(...),如下例所示:github.com/nestjs/swagger/issues/484
    猜你喜欢
    • 1970-01-01
    • 2020-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多