Created
February 16, 2023 06:03
-
-
Save dp0613/993d5097e02a5332494b1c41756559f7 to your computer and use it in GitHub Desktop.
Config basicAuth and JWT for swagger - NestJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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