Backend/SpringBoot

임시 비번 발급 후 비교할때 주의점(PasswordEncoder)

Dean83 2026. 2. 2. 14:14

실제 회원가입 등 비밀번호 저장을 DB에 할 때에는 PasswordEncoder 의 encode 메서드를 이용해서 저장만 하지, 실제 비교할 일은 거의 없었다. 보통은 이미 구현이 되어 있는 DaoAuthenticationProvider 에서 인증을 해주기 때문이다. 

 

임시번호 발급시 다양한 방법으로 확인 및 구현이 가능하겠으나, 현재 나의 경우는  DaoAuthenticationProvider 을 상속받아 구현하는 구현체를 만들어서 이곳에서 비교를 해야 하는 상황이다.

(만일 아이디 / 비번이 아닐경우 다른 Provider를 사용할 수 있고, 이 경우, AuthenticationManager 구현체를 디버깅 걸어서 확인필요)

 

알맞게 임시 비밀번호를 발급하고 입력했음에도 계속하여 로그인 실패가 나서 그 이유를 찾아보니, 다음과 같았다. 

 

  • PasswordEncoder 를 이용해 암호화 할 때 마다 값이 바뀐다. (BCryptEncoder)
  • PasswordEncoder 를 통해 matches 메서드를 이용해 사용자 입력값과 암호화된 비밀번호를 매칭한다.
    • 여기서 인자값 순서가 중요하다. 1번째 인자값이 사용자 입력값 (암호화 안된 순수 텍스트)
    • 2번째 인자값이 암호화된 비밀번호 이다. 

 

이거 순서가 중요한거 모르고 계속 헤맸어서 기록용으로 남겨둔다.

 

 

참고로, DaoAuthentication 을 상속받아 구현한 예는 아래와 같다. 

public class CustomDaoAuthenticationProvider extends DaoAuthenticationProvider {
    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails,
                                                  UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {

        String normalPassword = authentication.getCredentials().toString();
        CustomUserDetails customUserDetails = (CustomUserDetails) userDetails;
        boolean normalPasswordMatches = getPasswordEncoder().matches(normalPassword, customUserDetails.getPassword());
        if(normalPasswordMatches == false) {
            Instant temporaryPasswordCreatedAt = customUserDetails.getTemporaryPasswordCreatedAt();
            String temporaryPassword = customUserDetails.getTemporaryPassword();

            if(temporaryPasswordCreatedAt == null
                    || StringUtils.hasText(temporaryPassword) == false
                    || Instant.now().minus(3, ChronoUnit.MINUTES).isAfter(temporaryPasswordCreatedAt)) {
                throw new BadCredentialsException("Bad credentials");
            }

            boolean tempPasswordMatches = getPasswordEncoder().matches(normalPassword,
                    temporaryPassword);

            if(tempPasswordMatches == false) {
                throw new BadCredentialsException("Bad credentials");
            }
        }
    }
}