如何在 NestJS/Swagger 中禁用特定控制器方法的安全性?

问题描述 投票:0回答:3

我使用 NestJS 和 Swagger 模块来生成等效的 API 规范。 有没有办法在将控制器类标记为需要身份验证的同时禁用特定控制器方法的安全性? 示例:

// apply bearer auth security to controller
@ApiBearerAuth()
@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  // How can **getHello** method be made public???
  @Get()
  getHello(): string {
    return this.appService.getHello();
  }
}

与直接的方法相比,我正在寻找一种更直观的方法,其中每个控制器方法都应该用安全标记(公共方法除外)....

我尝试过使用

@ApiOperation({ security: [] })
但没有任何结果。它仍然从控制器类获取安全定义

authentication methods swagger overriding nestjs
3个回答
2
投票

看来这毕竟已经讨论过并且不会实现:github.com/nestjs/swagger/issues/1319


0
投票

可以添加

swagger/apiSecurity
元数据装饰器并在创建 swagger 文档后更新方法的安全性:

const PublicAuthMiddleware = SetMetadata(IS_PUBLIC_KEY, true);
const PublicAuthSwagger = SetMetadata('swagger/apiSecurity', ['public']);

export const Public = () => applyDecorators(
  PublicAuthMiddleware,
  PublicAuthSwagger,
)

无论你在哪里创建 swagger 文档(对我来说就是

main.ts
):

const document = SwaggerModule.createDocument(app, config);

Object.values((document as OpenAPIObject).paths).forEach((path: any) => {
    Object.values(path).forEach((method: any) => {
        if (Array.isArray(method.security) && method.security.includes('public')) {
            method.security = [];
        }
    });
});

(来源:https://github.com/nestjs/swagger/issues/892#issuecomment-1069549916


-1
投票

@ApiBearerAuth()
支持控制器和功能。您应该将
@ApiBearerAuth()
放入您需要的功能中

// apply bearer auth security to controller
@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  // How can **getHello** method be made public???
  @Get()
  getHello(): string {
    return this.appService.getHello();
  }

  @ApiBearerAuth()  <---- here
  @Post()
  createHello(): string {
    return this.appService.createHello();
  }

}
© www.soinside.com 2019 - 2024. All rights reserved.