13

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

Shivam Kubde
  • 545
  • 1
  • 8
  • 17
  • 1
    [express-basic-auth](https://github.com/LionC/express-basic-auth) can add Basic auth [to individual routes](https://github.com/LionC/express-basic-auth/issues/14#issuecomment-408375330), but I don't know if it can be used together with swagger-ui-express. – Helen Nov 19 '20 at 21:42

1 Answers1

18

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));
eol
  • 23,236
  • 5
  • 46
  • 64