관리 메뉴

Mini

[Nest JS] 로그인 구현 / bcrypt.compare salt issue 본문

JS/Nest.js

[Nest JS] 로그인 구현 / bcrypt.compare salt issue

Mini_96 2024. 8. 18. 21:36

* 서비스

async signIn(authCredentialDto : AuthCredentialsDto) {
  const {username, password} = authCredentialDto;
  const user = await this.userRepository.findOneBy({username});
  //username으로 user 찾고

  //입력받은 비밀번호랑 저장된 비밀번호랑 비교
  if(user && (await bcrypt.compare(password, user.password))){
    return 'login success'
  }
  else{
    throw new UnauthorizedException('login failed');
  }

}

📌 bcrypt.compare

DB에 실제 비밀번호가 아니라 해시값이 저장되어 있다. 그렇기 때문에 로그인할 때 실제 비밀번호가 아니라 해시값으로 비교를 해서 비밀번호 일치 여부를 따져봐야한다.

이때 bcrypt.compare를 사용해 비교하면 된다!

 

*  bcrypt.compare salt issue | salt 쳤는데 비교가능? ㅇㅇ

https://stackoverflow.com/questions/41564229/why-isnt-salt-required-to-compare-whether-password-is-correct-in-bcrypt

 

Why isn't salt required to compare whether password is correct in bcrypt?

I would like to use node.js bcrypt to hash passwords before storing them in the database. This link provides the documentation. https://github.com/kelektiv/node.bcrypt.js Here is an example on ha...

stackoverflow.com

 

salt를 분리하는것은 매우쉽기때문에 분리후 비밀번호만을 비교하면 된다!

 

* 컨트롤러

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

결과
잘못입력시 결과