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
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 !!
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.
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.
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With