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

Viewed 3198

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?

2 Answers

Yes, in your DocumentBuilder you may add:

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

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),
  );
}
Related