How to disable security for a specific controller method in NestJS/Swagger?
Asked Answered
V

3

6

I am using NestJS with Swagger Module to produce the equivalent API Spec. Is there a way to disable security for a specific controller method, while having marked the Controller class as requiring authentication? Example:

// 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();
  }
}

I am looking for a more intuitive way compared to the straightforward one where each controller method should be mark with security except for the public ones....

I have tried using @ApiOperation({ security: [] }) without any result. It still get's the security definition from the controller class

Visa answered 29/4, 2021 at 9:39 Comment(0)
V
2

It seems after all that this has been already discussed and will not be implemented: github.com/nestjs/swagger/issues/1319

Visa answered 29/4, 2021 at 17:47 Comment(0)
D
1

It is possible to add a swagger/apiSecurity metadata decorator and update the method's security after the swagger document is created:

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

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

And wherever you create your swagger document (for me it was the 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 = [];
        }
    });
});

(source: https://github.com/nestjs/swagger/issues/892#issuecomment-1069549916)

Delibes answered 30/1 at 11:1 Comment(0)
G
-1

@ApiBearerAuth() support Controller and function. You should put @ApiBearerAuth() into what function you need

// 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();
  }

}
Guerra answered 14/9, 2021 at 10:3 Comment(1)
As I stated in my question, I already know the method-specific way. I wanted to know whether an "exclude method from class" approach is possibleVisa

© 2022 - 2024 — McMap. All rights reserved.