Search code examples
typescriptswaggernestjsswagger-uinestjs-swagger

How to authorize multi api keys using @nestjs/swagger and @UseGuards?


I'm using @UseGuards to validate two api keys in header.

@Injectable()
export class AuthGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
  // check two api keys('some' and 'thing') in header at once
}

Also, I'm using @ApiHeader in Controller to show in swagger.

  @ApiOperation({ summary: 'blah blah' })
  @ApiHeader({ name: 'some'}, {name: 'thing'})
  @UseGuards(AuthGuard)
  @Get('/hello')
  async adminableCollections() {
    // do something
  }

I want to use @ApiSecurity or some what instead of @ApiHeader to authorize at one time using authorize button(in the picture), not entering values to every method. swagger Authorize button that can authorize all methods i want

I tried to add custom security using document builder, but it seems to not workig at all.

  const swaggerConfig = new DocumentBuilder()
    .setTitle('My API')
    .setDescription('Document for my api.')
    .setVersion('0.0.1')
    .addApiKey('some', { type: 'apiKey', in: 'header', name: 'some' })
    .addApikey('thing', { type: 'apiKey', in: 'header', name: 'thing })
    .build();

is there any way to solve it?


Solution

  • ok I solved with this issue

    AuthGuard was no needed in this problem. I just add apikeys in swagger config and add decorators on method I want.