在 NestJS 中,我可以在控制器级别添加什么装饰器以将 Authorization 标头添加到我的 Swagger 文档?

问题描述

我使用的是 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 文档时,虽然我可以输入“授权”标题值,

enter image description here

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

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

解决方法

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