[NestJS] 비밀번호 암호화, 로그인 기능 구현

·2023년 2월 12일
0

NestJS

목록 보기
1/6

비밀번호 암호화

모듈 생성 bcryptjs

npm install bcryptjs --save 

비밀번호를 데이터베이스에 저장하는 방법

1. 원본 비밀번호를 저장 (최악)

2. 비밀번호를 암호화 키(Encryption Key)와 함께 암호화(양방향)

  • 어떠한 암호를 이용해서 비밀번호를 암호화 하고 그 암호를 이용하여 복호화도 가능
  • 암호화 키가 노출되면 위험도 높음

    1234 ====>
    gUuFwNo4zkMV+erdGtBlf5NunNgcELQuiCFJmCU4F+E=
    gUuFwNo4zkMV+erdGtBlf5NunNgcELQuiCFJmCU4F+E=
    ====> 1234

3. SHA256 등으로 해시(Hash)해서 저장(단방향)

  • 레인보우 테이블을 만들어서 암호화된 비밀번호를 비교해서 비밀번호를 알아냄

레인보우 테이블

1234 ====> 03ac674216f3e15c761ee1a5e255f067953623c8b3
letmein ==> 1c8bfe8f801d79745c4631d09fff36c82aa37fc4cce4f
등등등 ... 대부분 유저들은 비슷한 암호를 사용
A 유저 비밀번호 1234
=== 03ac674216f3e15c761ee1a5e255f067953623c8b3
B 유저 비밀번호 1234
=== 03ac674216f3e15c761ee1a5e255f067953623c8b3

4. 솔트(salt) + 비밀번호(Plain Password)를 해시로 암호화해서 저장

  • 암호화 할 때 원래 비밀번호에다 salt(유니크값)를 붙인 후에 해시로 암호화

코드구현

추가

const salt = await bcript.genSalt();
const hashedPassword = await bcript.hash(password, salt);
const user = this.create({ username, password: hashedPassword });

Q. bcryptbcryptjs, 두 개의 라이브러리 중 bcryptjs를 쓴 이유

  • bcrypt는 특히 x86_64 또는 glibc 기반 배포판 이외의 아키텍처를 사용하는 경우 올바르게 빌드하기 위해 추가 단계가 필요한 경우가 있습니다. 소스에서 컴파일하려면 추가 종속성이 필요합니다.
  • bcryptjs는 일반 js이므로 브라우저를 포함한 모든 곳에서 작동합니다. bcrypt는 NodeJS, Node-WebKit 또는 Electron에서만 실행됩니다.
  • 결론으로는 설치에서 나는 에러를 방지하기 위해서 bcryptjs를 사용!

로그인 기능 구현

auth.service.ts

async signIn(authCredentialsDto:AuthCredentialsDto):Promise<string> {
    const { username, password } = authCredentialsDto;
    const user = await this.userRepository.findOne({ username });
    if(user && (await bcrypt.compare(user.password, password))) {
      return 'login success'
    } else {
      throw new UnauthorizedException('login failed')
    }
  }

auth.controller.ts

@Post('/signin')
  signIn(
    @Body(ValidationPipe) authCredentialsDto: AuthCredentialsDto,
  ): Promise<string> {
    return this.authService.signIn(authCredentialsDto);
  }

profile
개발자가 되는 과정

0개의 댓글