Backend/spring

비밀번호 암호화/인증 (spring security 계정 생성)

dddzr 2023. 11. 6. 13:31

 

암호화

사용자를 생성 할 때 DB에 암호화 하여 비밀번호 저장.

  @RequestMapping(value = "/passwordEncode", method = RequestMethod.POST)
  @ResponseBody
  public String passwordEncode(@RequestBody String password, HttpServletRequest request) {
    BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(10);
    String hashedPassword = passwordEncoder.encode(password);
    return hashedPassword;
  }

 

 


인증

passwordEncoder.matches(presentedPassword, userDetails.getPassword())를 사용하여 비밀번호 확인

*호출 순서 : SpringSecurityConfig.java > AbstractDaoAuthenticationConfigurer.class> DaoAuthenticationProvider.class

//SpringSecurityConfig.java
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    //login process
    auth.userDetailsService(memberService).passwordEncoder(new BCryptPasswordEncoder());
}
//AbstractDaoAuthenticationConfigurer.class
@SuppressWarnings("unchecked")
public C passwordEncoder(PasswordEncoder passwordEncoder) {
    provider.setPasswordEncoder(passwordEncoder);
    return (C) this;
}

 

*DaoAuthenticationProvider는 Spring Security에서 사용자의 인증을 처리하는 구현체 중 하나로 입력된 비밀번호를 데이터베이스에 저장된 비밀번호와 비교하여 인증을 수행하는 역할을 합니다.

//DaoAuthenticationProvider.class
	@SuppressWarnings("deprecation")
	protected void additionalAuthenticationChecks(UserDetails userDetails,
			UsernamePasswordAuthenticationToken authentication)
			throws AuthenticationException {
		if (authentication.getCredentials() == null) {
			logger.debug("Authentication failed: no credentials provided");

			throw new BadCredentialsException(messages.getMessage(
					"AbstractUserDetailsAuthenticationProvider.badCredentials",
					"Bad credentials"));
		}

		String presentedPassword = authentication.getCredentials().toString();

		if (!passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
			logger.debug("Authentication failed: password does not match stored value");

			throw new BadCredentialsException(messages.getMessage(
					"AbstractUserDetailsAuthenticationProvider.badCredentials",
					"Bad credentials"));
		}
	}