Skip to main content

Command Palette

Search for a command to run...

Thiết lập Private cho Swagger API doc

Published
1 min read

Hello! I'm Zu.Doan

Trong quá trình setup Swagger cho dự án, thì mình cũng chỉ cần follow theo docs của NestJs là setup thành công Swagger API doc cho service của mình.

Tuy nhiên Swagger API doc link này lại là public, ai cũng có thể truy cập được và điều đó không tốt một chút nào phải không.

Sau một thời gian ngắn gg search, mình tìm thấy một giải pháp đơn giản như sau:

  • Sử dụng module express-basic-auth
  • Setup basic auth (sử dụng user name & password) cho những route đang truy cập tới Swagger API doc của mình
import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { AppModule } from './modules/app.module';
import * as basicAuth from 'express-basic-auth';
require('dotenv').config();

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  // Setup Swagger
  app.use(['/api'], basicAuth({
    challenge: true,
    users: {
      [process.env.SWAGGER_USER]: process.env.SWAGGER_PASS,
    },
  }));

  const config = new DocumentBuilder()
  .setTitle('Swagger')
  .setDescription('The api-shops API description')
  .setVersion('1.0')
  .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api', app, document);

  // App listen
  await app.listen(3000);
}
bootstrap();

Và kết quả là

Screenshot from 2021-08-10 22-07-08.png

20 views

More from this blog

zujs

35 posts