• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

username뿐만 아니라 password까지 검증되는 이유

23.02.21 18:45 작성 23.02.21 18:48 수정 조회수 826

0

현재 강의까지의 인증 로직을 보면

@Service
@RequiredArgsConstructor
public class CustomUserDetailsService implements UserDetailsService {

    private final UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        Account account = userRepository.findByUsername(username);

        if (account == null) {
            throw new UsernameNotFoundException("UsernameNotFoundException");
        }

        List<GrantedAuthority> roles = new ArrayList<>();
        roles.add(new SimpleGrantedAuthority(account.getRole()));

        AccountContext accountContext = new AccountContext(account, roles);

        return accountContext;
    }


}

useranme으로만 Account객체를 조회해서 이것이 null인지 아닌지로 사용자를 인증하는 로직으로 이해했습니다.

하지만 로그인 페이지에서 DB에 존재하는 username을 알맞게 입력하고 password는 틀리게 입력하면 인증단계에서 걸러지는걸 확인했습니다. 그렇다면 password까지 검증을 한다는 것인데..

분명 인증로직으로만 봤을땐 username으로만 인증을 하는것 같았는데 password까지 검증될 수 있었던 이유가 무엇인가요.?

 

답변 1

답변을 작성해보세요.

0

password 검증은 CustomUserDetailsService 에서 하지 않고 일반적으로 AuthenticationProvider 타입의 구현체( 기본은 DaoAuthenticationProvider) 에서 처리하게 됩니다

DaoAuthenticationProvider.java 인데 아래 코드를 보시면 패스워드를 비교 검증하고 있습니다.

@Override
@SuppressWarnings("deprecation")
protected void additionalAuthenticationChecks(UserDetails userDetails,
                                              UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
    if (authentication.getCredentials() == null) {
        this.logger.debug("Failed to authenticate since no credentials provided");
        throw new BadCredentialsException(this.messages
                .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
    }
    String presentedPassword = authentication.getCredentials().toString();
    if (!this.passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
        this.logger.debug("Failed to authenticate since password does not match stored value");
        throw new BadCredentialsException(this.messages
                .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
    }
}
if (!this.passwordEncoder.matches(presentedPassword, userDetails.getPassword()))

시큐리티가 내부적으로 이러한 처리를 해주고 있으며 필요할 경우 사용자가 직접 AuthenticationProvider 의 구현체를 생성해서 검증처리를 할 수 있습니다.

강의 내용에도 나와 있으니 참고해 주시기 바랍니다.

조우현님의 프로필

조우현

질문자

2023.02.21

감사합니다