Auth Decorator

In the initial configuration of Swagger that was done in the Setup Section, the following line was added:

.addBearerAuth({ in: 'header', type: 'http' })

With this line we indicate that we will use a bearer token to authenticate the user, but for this to work you must use the @ApiBearerAuth decorator.

Example:

@ApiBearerAuth() example

Multiple Authentication Methods

If you want to add another authentication method, you can do it in the generated configuration in src/main.ts file, and also add your decorators in the controllers where you want to use these authentication methods.

In this configuration you have 3 authentication methods:

  • Bearer Token.

  • Api Key.

  • Basic Auth.

Example:

const appName = process.env.APP_NAME || 'Backend API';
const options = new DocumentBuilder()
  .setTitle(appName)
  .setVersion('1.0')
  .addBearerAuth({ in: 'header', type: 'http' })
  .addApiKey()
  .addBasicAuth()
  .build();
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup('/', app, document, { customSiteTitle: appName });

Then, when you want to authenticate to the Swagger interface, you can choose any of these methods. This is how it would look:

Swagger Interface - Multiple authentication methods

Last updated

Was this helpful?