Tech Blog of Pinomaker
article thumbnail

0. 들어가기 전

Web에서는 API에 대한 Request와 Response에 대해서 브라우저의 네트워크 탭을 열어 정보를 확인할 수 있다. 따라서 request에 대한 값과 response에 대한 값은 암호화 처리를 통해 외부에 데이터가 노출되지 않게 해야한다.

 

nestjs에서는 해당 작업을 하기 위해 라이브러리를 개발 후 npm에 배포 하였다. 해당 글은 사용 방법을 정리한다.

 

 

nest-encrypt-cycle

A NestJS interceptor that encrypts/decrypts request and response bodies. Latest version: 1.1.1, last published: a day ago. Start using nest-encrypt-cycle in your project by running `npm i nest-encrypt-cycle`. There are no other projects in the npm registry

www.npmjs.com

 

01. 모듈 설치

먼저 프로젝트에 nest-encrypt-cycle 모듈을 설치한다.

pnpm add nest-encrypt-cycle

 

02. app.module.ts에 import 

app.module.ts에 EncryptModule을 import 해야하는 데, 이 때 암호화에 사용할 key와 암호화를 적용하지 않은 WHITE_LIST를 넣으면 된다.

 

// ** Nest Imports
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';

// ** Module Imports
import { EncryptModule } from 'nest-encrypt-cycle';
import { WHITE_LIST } from './global/constants/whitelist';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      envFilePath: [`.env.${process.env.NODE_ENV}`],
    }),
    // EncryptModule Import 처리
    EncryptModule.register({
      // 암호화에 사용할 키 등록
      key: process.env.AES_HASH_KEY || '1234123412341234',
      // 암호화를 하지 않을 api 등록
      whiteList: [...WHITE_LIST],
    })
  ],
  controllers: [],
  exports: [],
  providers: [],
})
@Module({
  imports: [],
})
export class AppModule {}

 

 

whiteList의 타입은 아래와 같으며 Health Check와 같이 암호화가 필요 없는 경우 넣어주면 된다.

export interface EncryptOptions {
    key: string;
    whiteList: {
        method: string;
        pathname: string;
    }[];
}


export const WHITE_LIST : EncryptOptions[] = [
  {
    pathname: '/api/v1/health',
    method: 'GET',
  }
];

 

또한 무조건 암호화 처리하는 것이 아닌 request header에 is-encrypted를 Y로 넣어줘야 작동하게 된다. F.E에서도 request, response에 암호화 및 복호화 처리를 넣어주면 아래와 같이 request, response에 대해 암호화 처리되어 안전한 서비스를 운영할 수 있다.

profile

Tech Blog of Pinomaker

@pinomaker

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!