[오류해결] BadCredentialsException: 자격 증명에 실패하였습니다.

김상우·2023년 10월 17일
0

포트폴리오 Jwt를 구현하다가 부딪힌 오류다.

    // CustomUserDetailsServce에서 만든 loadUserByUserName이 실행된다.
    
    Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);

이 부분에서 오류가 났는데,

커스텀으로 만든 userDetail을 일단 보여주자면

  @Override
  @Transactional
  // 로그인시에 DB에서 유저정보와 권한정보를 가져와서 해당 정보를 기반으로 userdetails.User 객체를 생성해 리턴
  public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {

    return customerRepository.findOneWithAuthoritiesByCustomerEmail(username)
        .map(user -> createUser(username, user))
        .orElseThrow(() -> new UsernameNotFoundException(username + " -> 유저를 찾을 수 없습니다."));
  }

  private org.springframework.security.core.userdetails.User createUser(String username, Customer customer) {
    if (!customer.isActivated()) {
      throw new RuntimeException(username + " -> 활성화되어 있지 않습니다.");
    }

    List<GrantedAuthority> grantedAuthorities = customer.getAuthorities()
        .stream()
        .map(authority -> new SimpleGrantedAuthority(authority.getAuthority()))
        .collect(Collectors.toList());

    return new User(customer.getCustomerName(), bCryptPasswordEncoder.encode(customer.getPassword()), grantedAuthorities);
  }
}

loadUserByUsername 메소드를 사용하는데

새로운 유저를 만들어 security context에 넣어주는 과정에서

이미 저 customer 라는 객체를 파라미터로 받을때

내부의 password는 암호화가 되어있었는데

위 코드를 리턴할때 한번더 암호화를 해버렸고 그 결과

.authenticate()메소드를 구현하는

AbstractUserDetailsAuthenticationProvider 라는 추상 클래스에서

additionalAuthenticationChecks() 라는 메소드 안에서 오류가 발생했다.

		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"));
		}
	}

BcyptEncoder를 통해

userDetail 과 UsernamePasswordAuthenticationToken 의

비밀번호가 매치 하는지 확인하는 와중에 에러가 발생한 것 같다.

해서

  private org.springframework.security.core.userdetails.User createUser(String username, Customer customer) {
    if (!customer.isActivated()) {
      throw new RuntimeException(username + " -> 활성화되어 있지 않습니다.");
    }

    List<GrantedAuthority> grantedAuthorities = customer.getAuthorities()
        .stream()
        .map(authority -> new SimpleGrantedAuthority(authority.getAuthority()))
        .collect(Collectors.toList());

    return new User(customer.getCustomerEmail(), customer.getPassword(), grantedAuthorities);
  }

로 변경해 오류를 해결했다.

profile
헤헤

0개의 댓글