Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to add Authentication to access to NestJS' Swagger Explorer

I'm currently using Swagger in my NestJS project, and I have the explorer enabled:

in main.js

const options = new DocumentBuilder()     .setTitle('My App')     .setSchemes('https')     .setDescription('My App API documentation')     .setVersion('1.0')     .build()  const document = SwaggerModule.createDocument(app, options) SwaggerModule.setup('docs', app, document, {     customSiteTitle: 'My App documentation', }) 

With this, the explorer is accessible in /docs which is what I expected. But I was wondering if it's possible to add any Authentication layer to the explorer, so only certain requests are accepted.

I want to make this explorer accessible in production, but only for authenticated users.

Thanks in advance :)

like image 678
josec89 Avatar asked Feb 21 '19 08:02

josec89


People also ask

How do I give authorization token in swagger UI?

Token-based Authentication To retrieve a token via our Swagger UI, send a POST request like the following to the /api-token-auth/ endpoint. Copy the token generated from the response, excluding the quotation marks. Click the Authorize button and enter "Bearer", followed by the token from step 2. Click Authorize.

How do I enable swagger authorization?

0+, you can use the preauthorizeBasic method to pre-fill the Basic auth username and password for "try it out" calls. "Try it out" will use the specified username and password, and if you click the "Authorize" button in Swagger UI, you will see that the username and masked password are pre-filled in the UI.


1 Answers

Securing access to your Swagger with HTTP Basic Auth using NestJS with Express

First run npm i express-basic-auth then add the following to your main.{ts,js}:

// add import import * as basicAuth from 'express-basic-auth';  // ...  // Sometime after NestFactory add this to add HTTP Basic Auth app.use(     ['/docs', '/docs-json'],     basicAuth({         challenge: true,         users: {             yourUserName: 'p4ssw0rd',         },     }), );   // Your code const options = new DocumentBuilder()     .setTitle('My App')     .setSchemes('https')     .setDescription('My App API documentation')     .setVersion('1.0')     .build()  const document = SwaggerModule.createDocument(app, options) SwaggerModule.setup('docs', app, document, {     customSiteTitle: 'My App documentation', })  // ... 

With this in place you will be prompted on any of the /docs route with a HTTP Basic Auth prompt. We have to name /docs-json explicitly too, to protect the generated JSON OpenAPI file.

You should not put the credentials in your code/repository but rather in your .env and access via the ConfigService.

I have seen this solution first here.

like image 190
KiwiKilian Avatar answered Sep 20 '22 19:09

KiwiKilian