NightMNKY
NightMNKY

Reputation: 311

How to globally apply Swagger UI's @ApiBearerAuth() instead of applying for each controller

I am working on a nestJS based api, and I am using Swagger UI documentation. I want keep the functionality of @ApiBearerAuth() for all my controllers, however I wish to have this as a global feature. That way every time I create new routes or endpoints it will already be covered.

From the https://docs.nestjs.com/openapi/security documentation:

@ApiBearerAuth()
@Controller('cats')
export class CatsController {}

This is what I am following now, but is there a way to set this globally?

Upvotes: 9

Views: 12025

Answers (3)

rya brody
rya brody

Reputation: 286

In the source code of @nestjs/swagger its visible that addBearerAuth() sets the security name to "bearer" so it is possible to use addBearerAuth() and addSecurityRequirements('bearer'):

const config = new DocumentBuilder()
  ...
  .addBearerAuth()
  .addSecurityRequirements('bearer')
  .build();

Upvotes: 8

Nine Magics
Nine Magics

Reputation: 737

Yes, in your DocumentBuilder you may add:

.addSecurity('ApiKeyAuth', {
    type: 'apiKey',
    in: 'header',
    name: 'Authorization',
})
.addSecurityRequirements('ApiKeyAuth')

Upvotes: 3

harian
harian

Reputation: 445

This is a little hack, because I use ApiTags in every Controller so that I create a new decorator

import { applyDecorators } from '@nestjs/common';

export function ApiTagsAndBearer(...tags: string[]) {
  return applyDecorators(
    ApiBearerAuth(), //
    ApiTags(...tags),
  );
}

Upvotes: 2

Related Questions