Is it possible to add Authentication to access to NestJS' Swagger Explorer
UPDATE
As per recent changes in DocumentBuilder
methods, this how it worked for me. Sharing for the people who are using new versions.
const options = new DocumentBuilder().setTitle('My API').setDescription('API used for testing purpose').setVersion('1.0.0').setBasePath('api').addBearerAuth( { type: 'http', scheme: 'bearer', bearerFormat: 'JWT' }, 'access-token',).build();const document = SwaggerModule.createDocument(app, options);
Update Also, please use @ApiBearerAuth()
on your controller function to add auth.
@Get('/test')@ApiBearerAuth()
access-token
is the name for reference in swagger doc. Your token in the header will be passed as below:
curl -X GET "http://localhost:3004/test" -H "accept: application/json" -H "Authorization: Bearer test-token"
Just add .addBearerAuth()
(without any parameters) to your swagger options
and @ApiBearerAuth()
to your Controller methods
const options = new DocumentBuilder() .setTitle('My App') .setSchemes('https') .setDescription('My App API documentation') .setVersion('1.0') .addBearerAuth() .build()
Securing access to your Swagger with HTTP Basic Auth using NestJS with Express
First run npm i express-basic-auth
then add the following to your main.{ts,js}
:
// add importimport * as basicAuth from 'express-basic-auth';// ...// Sometime after NestFactory add this to add HTTP Basic Authapp.use( ['/docs', '/docs-json'], basicAuth({ challenge: true, users: { yourUserName: 'p4ssw0rd', }, }),);// Your codeconst options = new DocumentBuilder() .setTitle('My App') .setSchemes('https') .setDescription('My App API documentation') .setVersion('1.0') .build()const document = SwaggerModule.createDocument(app, options)SwaggerModule.setup('docs', app, document, { customSiteTitle: 'My App documentation',})// ...
With this in place you will be prompted on any of the /docs
route with a HTTP Basic Auth prompt. We have to name /docs-json
explicitly too, to protect the generated JSON OpenAPI file.
You should not put the credentials in your code/repository but rather in your .env
and access via the ConfigService.
I have seen this solution first here.