Is it possible to add Authentication to access to NestJS' Swagger Explorer?

Answer

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 import
import * as basicAuth from 'express-basic-auth';

// ...

// Sometime after NestFactory add this to add HTTP Basic Auth
app.use(
['/docs', '/docs-json'],
basicAuth({
challenge: true,
users: {
yourUserName: 'p4ssw0rd',
},
}),
);


// Your code
const 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.

 

 

 

 

 

 

All react js Questions

Ask your interview questions on react-js

Write Your comment or Questions if you want the answers on react-js from react-js Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---