본문 바로가기
Research/Nest.js

nestjs_swagger API 보안 설정

by RIEM 2023. 4. 8.
728x90

nest.js swagger API 페이지 보안 설정하기

express-basic-auth(https://www.npmjs.com/package/express-basic-auth)

express 라이브러리이지만 nest.js를 express 기반으로 설정했다면 문제없이 사용할 수 있다.

npm install express-basic-auth

 

// main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { HttpExceptionFilter } from './common/exceptions/http-exception.filter';
import { ValidationPipe } from '@nestjs/common';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import * as expressBasicAuth from 'express-basic-auth';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe());
  app.useGlobalFilters(new HttpExceptionFilter());

  // * Swagger API 보안 설정
  app.use(
    ['/docs', '/docs-json'],
    expressBasicAuth({
      challenge: true,
      users: {
        [process.env.SWAGGER_USER]: process.env.SWAGGER_PASSWORD,
      },
    }),
  );

  // * Swagger 셋업
  const config = new DocumentBuilder()
    .setTitle('Swagger for Cats')
    .setDescription('The cats API description')
    .setVersion('1.0')
    .build();
  const document = SwaggerModule.createDocument(app, config);
  // Swagger endpoint : ex) localhost:8000/docs
  SwaggerModule.setup('docs', app, document);

  // * CORS 셋업
  app.enableCors({
    origin: true, // true 시 모든 url에 개방(개발 환경). 특정 url만 허용할 수 있음(배포 환경)
    credentials: true, // 프론트에서 credentials 설정을 true 해주었기 때문
  });

  const PORT = process.env.PORT;
  await app.listen(PORT);
}
bootstrap();

app.use()로 express 미들웨어를 사용하여 expressBasicAuth 라이브러리를 적용해주었다. /docs, /docs-json 엔드포인트에 접근하면 아이디와 비밀번호를 요청하게 된다.

ID, PW를 기입하면 스웨거 페이지를 잘

728x90

댓글