Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure security to allow swagger url to be accessed only with authentication in nodejs

I have integrated swagger in node and it is accessible on http://localhost:3002/api-docs. But the swagger ui is publicly accessible. I want to add authentication/security to access this route. When user hits http://localhost:3002/api-docs, it should show popup/prompt to enter username/password. If username and password is correct then only user should able to see swagger UI.

Possibly like as seen in below screenshot

enter image description here

I am using swagger-ui-express, and this is my code that I m using

import swaggerUi from 'swagger-ui-express';
import * as swaggerDocument from './swagger.json' 

....
....

app.use("/api-docs",swaggerUi.serve,swaggerUi.setup(swaggerDocument));


I searched on the internet but didn't got any solution. I found one solution but that is in spring.

Thanks in advance !!

like image 574
Shivam Kubde Avatar asked Nov 19 '20 14:11

Shivam Kubde


People also ask

How do I add security to swagger?

After you have defined the security schemes in the securitySchemes section, you can apply them to the whole API or individual operations by adding the security section on the root level or operation level, respectively.

How do I enable basic authentication in swagger UI?

Basic authentication is easy to define. In the global securityDefinitions section, add an entry with type: basic and an arbitrary name (in this example - basicAuth). Then, apply security to the whole API or specific operations by using the security section.

How do I protect my swagger API?

Password protection. So first let's protect the Swagger UI with HTTP basic auth requiring visitors to enter a username and password to access /docs or /docs-json . This can easily be done by implementing express-basic-auth, a simple plug & play HTTP basic auth middleware for Express.


1 Answers

You can plug in a basic-auth middleware (e.g. https://github.com/LionC/express-basic-auth) to protect the swagger-ui route. If you use express-basic-auth, make sure to set the challenge option in order to force the browser to open a prompt:

const basicAuth = require('express-basic-auth');

app.use("/api-docs",basicAuth({
    users: {'yourUser': 'yourPassword'},
    challenge: true,
}), swaggerUi.serve, swaggerUi.setup(swaggerDocument));
like image 119
eol Avatar answered Nov 01 '22 02:11

eol