NestJS 애플리케이션에서 OpenAPI 사양 및 Swagger UI를 보호하는 방법

15458 단어 nestjsnode
Nest의 멋진 점 중 하나는 API에 대한 OpenAPI 사양을 거의 자동으로 생성할 수 있는 전용 OpenAPI 모듈입니다. 실제로 여기 저기 데코레이터를 추가하고 짜잔.

"OAS(OpenAPI 사양)는 RESTful API에 대한 표준 언어 불가지론적 인터페이스를 정의하여 사람과 컴퓨터 모두가 소스 코드, 문서에 액세스하지 않고도 또는 네트워크 트래픽 검사를 통해 서비스 기능을 발견하고 이해할 수 있도록 합니다."OpenAPI 사양에 대해here .

그러나 OAS는 이름 그대로 공개하는 것을 목표로 하므로 모든 사람이 API 사양을 사용할 수 있도록 하는 것이 항상 원하는 것은 아닐 수도 있습니다. 예를 들어 프로젝트의 API가 공개되지 않은 경우입니다.

팀 구성원에게만 액세스 권한을 부여하여 OAS 및 Swagger UI의 이점을 누리려면 어떻게 해야 할까요?

내 전략은 일반적으로 Swagger UI를 비밀번호로 보호하고 프로덕션에서 완전히 숨기는 것입니다. 이것이 당신이 그것을 달성할 수 있는 방법입니다.

시작하기



Nest 문서에 따라 필요한 모든 종속성을 설치한 후 main.ts는 다음과 같이 보일 수 있습니다.

// main.ts

import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';

import { AppModule } from './app.module';

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

  const config = new DocumentBuilder()
    .setTitle('API Docs')
    .setDescription('The API documentation')
    .setVersion('1.0')
    .build();

  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('docs', app, document);

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



Swagger UI는 브라우저에서 http://localhost:8000/docs을 방문하여 실행됩니다.

비밀번호 보안



따라서 먼저 방문자가 /docs 또는 /docs-json에 액세스하기 위해 사용자 이름과 비밀번호를 입력하도록 요구하는 HTTP basic auth으로 Swagger UI를 보호하겠습니다. 이것은 Express용 간단한 플러그 앤 플레이 HTTP 기본 인증 미들웨어인 express-basic-auth을 구현하여 쉽게 수행할 수 있습니다.
npm i express-basic-authexpress-basic-auth를 설치한 후 /docs/docs-json 엔드포인트에 대해 이 미들웨어를 활성화할 수 있습니다. 이렇게 하려면 다음과 같이 main.ts를 수정하십시오.

// main.ts

import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import * as basicAuth from 'express-basic-auth';

import { AppModule } from './app.module';

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

  app.use(['/docs', '/docs-json'], basicAuth({
    challenge: true,
    users: {
      [process.env.SWAGGER_USER]: process.env.SWAGGER_PASSWORD,
    },
  }));

  const config = new DocumentBuilder()
    .setTitle('API Docs')
    .setDescription('The API documentation')
    .setVersion('1.0')
    .build();

  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('docs', app, document);

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



이것을 작동시키는 열쇠는 올바른 순서이며, Swagger를 초기화하기 전에 미들웨어app.use(['/docs', '/docs-json'], basicAuth({…})를 적용하는 것이 중요합니다.
basicAuth() 이 시나리오에서는 사용자의 개체가 필요합니다. 여기서는 하나만 사용하고 있습니다. 자격 증명을 하드코딩하지 않는 것이 항상 좋은 생각이므로 환경 변수에 의존하는 것이 여기에서 좋은 선택임을 명심하십시오. express-basic-auth 에 대한 몇 가지 구성 옵션을 사용할 수 있습니다. docs 을 확인하십시오.

프로덕션에서 Swagger UI 숨기기



언급했듯이 내가 하는 두 번째 일은 프로덕션에서 Swagger UI를 완전히 숨기는 것입니다. 가장 간단한 방법은 Swagger를 초기화하는 부분 주위에 조건문을 래핑하는 것입니다. 이것 좀 봐:

// main.ts

import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import * as basicAuth from 'express-basic-auth';

import { AppModule } from './app.module';

const SWAGGER_ENVS = ['local', 'dev', 'staging'];

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

  if (SWAGGER_ENVS.includes(process.env.NODE_ENV)) {
    app.use(['/docs', '/docs-json'], basicAuth({
      challenge: true,
      users: {
        [process.env.SWAGGER_USER]: process.env.SWAGGER_PASSWORD,
      },
    }));

    const config = new DocumentBuilder()
      .setTitle('API Docs')
      .setDescription('The API documentation')
      .setVersion('1.0')
      .build();

    const document = SwaggerModule.createDocument(app, config);
    SwaggerModule.setup('docs', app, document);
  }

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



이것은 기본적으로 기본 인증 미들웨어만 적용하고 NODE_ENVlocal , dev 또는 staging 일 때 Swagger를 초기화합니다. 환경 이름을 처리하는 방법이나 제품 배포를 확인하는 다른 메커니즘이 있는지에 따라 프로젝트에서 약간 다르게 보일 수 있지만 요점은 알 수 있습니다.

그게 다야!

좋은 웹페이지 즐겨찾기