Shivam Kubde
Shivam Kubde

Reputation: 623

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 !!

Upvotes: 14

Views: 10231

Answers (1)

eol
eol

Reputation: 24555

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));

Upvotes: 22

Related Questions