rin
rin

Reputation: 75

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?

Upvotes: 2

Views: 6865

Answers (2)

AuthGuard isn't needed for this.

And in case someone needs an example

main.ts

import {DocumentBuilder, SwaggerModule} from '@nestjs/swagger'

const swaggerConfig = new DocumentBuilder()
  .setTitle('API REST')
  .addApiKey({type: 'apiKey', name: 'Api-Key', in: 'header'}, 'Api-Key')
  .build()
const document = SwaggerModule.createDocument(api, swaggerConfig)
SwaggerModule.setup('api', api, document)

controller.ts

import {ApiSecurity} from '@nestjs/swagger'

@ApiSecurity('Api-Key')
@Controller({path: 'entities'})
export class EntityController {
  ...
}

Upvotes: 11

rin
rin

Reputation: 75

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.

Upvotes: 0

Related Questions