Skip to content

Instantly share code, notes, and snippets.

@dp0613
Created February 16, 2023 06:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dp0613/993d5097e02a5332494b1c41756559f7 to your computer and use it in GitHub Desktop.
Save dp0613/993d5097e02a5332494b1c41756559f7 to your computer and use it in GitHub Desktop.
Config basicAuth and JWT for swagger - NestJS
import * as dotenv from 'dotenv';
dotenv.config();
import { NestFactory } from '@nestjs/core';
import { INestApplication } from '@nestjs/common';
import * as basicAuth from 'express-basic-auth';
import {
SwaggerModule,
DocumentBuilder,
SwaggerDocumentOptions,
SwaggerCustomOptions,
} from '@nestjs/swagger';
import { SecuritySchemeObject } from '@nestjs/swagger/dist/interfaces/open-api-spec.interface';
import { AppModule } from './app.module';
function boostrapSwagger(app: INestApplication) {
app.use(
['/apidocs', '/apidocs-json'],
basicAuth({
challenge: true,
users: {
[process.env.SWAGGER_USER]: process.env.SWAGGER_PASSWORD,
},
}),
);
const options: SwaggerDocumentOptions = {
deepScanRoutes: true,
};
const customOptions: SwaggerCustomOptions = {
customSiteTitle: 'My API Docs',
swaggerOptions: {
tagsSorter: 'alpha',
operationsSorter: 'alpha',
persistAuthorization: true,
},
};
const jwtBearerOptions: SecuritySchemeObject = {
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT',
name: 'JWT',
description: 'Enter JWT token',
in: 'header',
};
const config = new DocumentBuilder()
.setTitle('My API Docs')
.setDescription('API documentation v1')
.setVersion('1.0')
.addBearerAuth(jwtBearerOptions, 'jwt')
.build();
const document = SwaggerModule.createDocument(app, config, options);
SwaggerModule.setup('api', app, document, customOptions);
}
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.enableCors();
if (['development', 'staging'].includes(process.env.NODE_ENV)) {
boostrapSwagger(app);
}
await app.listen(parseInt(process.env.BE_PORT) || 8080, '0.0.0.0');
}
bootstrap();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment