2Ruk / nestjs-study

nestjs-study
0 stars 0 forks source link

[2 주차] 학습 내용 정리 #12

Closed DaHoon06 closed 8 months ago

DaHoon06 commented 8 months ago

bcrypt

bcrypt는 패스워드를 해싱할 때 내부적으로 랜덤 한 salt를 생성하기 때문에 같은 문자열에 대해서 매번 다른 해싱 결과를 반환합니다.

salt가 통합된 형식으로 인해 레인보우 테이블(rainbow table) 공격을 방지할 수 있으며, 반복 횟수를 늘려서 연산 속도를 늦출 수 있기 때문에 연산 능력이 증가하더라도 브루트 포스(brute force) 검색 공격에 대비할 수 있습니다.

또한 해시 값 내부에 salt 값이 포함되기 때문에 salt 값을 따로 저장하지 않아도 해싱 된 값과 평문을 비교할 수 있다는 특징이 있습니다.

Reference

https://inpa.tistory.com/entry/NODE-%F0%9F%93%9A-bcrypt-%EB%AA%A8%EB%93%88-%EC%9B%90%EB%A6%AC-%EC%82%AC%EC%9A%A9%EB%B2%95

# npm
https://www.npmjs.com/package/bcrypt

jwt (Json Web Token)

전자 서명 된 URL-safe (URL로 이용할 수있는 문자 만 구성된)의 JSON

JWT는 속성 정보 (Claim)를 JSON 데이터 구조로 표현한 토큰으로 RFC7519 표준

JWT는 서버와 클라이언트 간 정보를 주고 받을 때 HTTP Request Header 에 JSON 토큰을 넣은 후 서버는 별도의 인증 과정없이 헤더에 포함되어 있는 JWT 정보를 통해 인증합니다

이 때 사용되는 JSON 데이터는 URL-Safe 하도록 URL에 포함할 수 있는 문자만으로 만듭니다.

JWT의 구조

JWT는 Header, Payload, Signature 3개로 구성되어있습니다.

스크린샷 2024-01-03 오후 9 41 30

Header

alg : Signature에서 사용하는 알고리즘 typ : 토큰 타입 Signature에서 사용하는 알고리즘은 대표적으로 RS256(공개키/개인키)와 HS256(비밀키(대칭키))

Payload

사용자 정보가 들어있습니다.

sub : 토큰 제목(subject) aud : 토큰 대상자(audience) iat : 토큰이 발급된 시각 (issued at) exp : 토큰의 만료 시각 (expired)

Signature

Signature는 헤더와 페이로드의 문자열을 합친 후에, 헤더에서 선언한 알고리즘과 key를 이용해 암호한 값

Header와 Payload는 단순히 [Base64url] 로 인코딩되어 있어 누구나 쉽게 복호화할 수 있지만, Signature는 key가 없으면 복호화할 수 없습니다.

guard

요청의 처리 여부를 결정하는 미들웨어 역할 (인증과 권한 부여 등 요청에 대한 검사를 처리하는 데 주로 사용)

@nestjs/common의 CanActivate 인터페이스를 확장하는 클래스로 구현됩니다. 이 인터페이스는 canActivate라는 단일 메서드를 정의하며, 이 메서드는 ExecutionContext 객체를 인수로 취하고 요청이 진행되어야 하는지 여부를 나타내는 부울 값을 반환

// UseGuard 내부

import { CanActivate } from '../../interfaces';
/**
 * Decorator that binds guards to the scope of the controller or method,
 * depending on its context.
 *
 * When `@UseGuards` is used at the controller level, the guard will be
 * applied to every handler (method) in the controller.
 *
 * When `@UseGuards` is used at the individual handler level, the guard
 * will apply only to that specific method.
 *
 * @param guards a single guard instance or class, or a list of guard instances
 * or classes.
 *
 * @see [Guards](https://docs.nestjs.com/guards)
 *
 * @usageNotes
 * Guards can also be set up globally for all controllers and routes
 * using `app.useGlobalGuards()`.  [See here for details](https://docs.nestjs.com/guards#binding-guards)
 *
 * @publicApi
 */
export declare function UseGuards(...guards: (CanActivate | Function)[]): MethodDecorator & ClassDecorator;

Reference

https://develop-const.tistory.com/12

configService

활용 - app.module 에 ConfigModule 설정

import { Module } from '@nestjs/common';
import { RecipesModule } from '@modules/recipes/recipes.module';
import { IngredientsModule } from '@modules/ingredients/ingredients.module';
import { UsersModule } from '@modules/users/users.module';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { ReplyModule } from "@modules/reply/reply.module";
import {MongooseModule} from "@nestjs/mongoose";
import { AppGuardModule } from '@src/guards/app.guard.module';

const IS_PROD = process.env.NODE_ENV === 'production';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      envFilePath: '.env',
    }),
    MongooseModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: async (configService: ConfigService) => ({
        uri: configService.get<string>('MONGO_URI'),
      }),
      inject: [ConfigService],
    }),
    AppGuardModule,
    RecipesModule,
    IngredientsModule,
    UsersModule,
    ReplyModule,
  ],
})
export class AppModule {}

공식 문서

https://docs.nestjs.com/techniques/configuration

Reference

https://velog.io/@kakasoo/Nest%EC%97%90%EC%84%9C-ConfigModule-TypeORM-%EC%93%B0%EA%B8%B0