Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NestJS - Protect access to Swagger UI

I have a project API Rest with NestJS, implements Swagger. Everything working fine, but I need protect the access to Swagger UI. Is possible protect the Swagger UI with simply user/pass or something like this?

like image 320
Diego Roque Avatar asked Oct 18 '25 08:10

Diego Roque


1 Answers

Yes, it is possible to restrict accessing Swagger UI with basic authorization.

You can use this package for basic auth: express-basic-auth

After installing express-basic-auth you would want to enable this middleware for your endpoint.

app.use(['/swagger'], basicAuth({
    challenge: true,
    users: {
       [process.env.SWAGGER_USER]: process.env.SWAGGER_PASSWORD,
    },
}));

It is important to apply the middleware app.use(['/swagger'], basicAuth({…}) before you initialize Swagger.

If you want to hide Swagger UI on production, check this article: https://manuel-heidrich.dev/blog/how-to-secure-your-openapi-specification-and-swagger-ui-in-a-nestjs-application/

Information is also taken from that article!

like image 135
Eugene09 Avatar answered Oct 21 '25 15:10

Eugene09