1.의의

2.구현

  1. securityconfig.java
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	
    @Autowired
    private CustomAuthenticationProvider cuap;
	
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		
		cuap.setUserDetailsService((CustomUserDetailsService)customUserDetailsService());
		auth.authenticationProvider(cuap);
	}

@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.formLogin()
		.loginPage("/auth/login");

		...

		
		http.addFilterAt(new CustomUsernamePasswordAuthenticationFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class);
	}

@Bean
	public UserDetailsService customUserDetailsService() {
		return new CustomUserDetailsService();
	}

2.CustomAuthenticationProvider.java

KakaoTalk_20220907_093827124.jpg


@Slf4j
@Component
public class CustomAuthenticationProvider implements **AuthenticationProvider** {

    private CustomUserDetailsService userDetailsService;  //전 장의 userDetailService  참조
    
	@Autowired
	private PasswordEncoder passwordEncoder;
	
	@Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		log.info("authenticate");
		
		CustomUsernamePasswordAuthenticationToken token = (CustomUsernamePasswordAuthenticationToken)authentication;
        String userName = token.getName();
        String secretNumber = token.getSecretNumber();
        
        log.info("authenticate userName " + userName);

        UserDetails user = userDetailsService.loadUserByUsername(userName);
        log.info("user: {}", user);

        if(user == null) {
            throw new UsernameNotFoundException("Invalid username/password");
        }
        
        String encodedPassword = user.getPassword();
        String credentials = (String)token.getCredentials();
        
        log.info("authenticate encodedPassword " + encodedPassword);
        log.info("authenticate token.getCredentials() " + credentials);
        log.info("authenticate encodedCredentials " + passwordEncoder.matches(credentials, encodedPassword));
        
        if(!passwordEncoder.matches(credentials, encodedPassword)) {	
            throw new BadCredentialsException("Invalid username/password");
        }
        
        Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
        
        log.info("authorities: {}", authorities);
        
        return new CustomUsernamePasswordAuthenticationToken(user, encodedPassword, secretNumber, authorities);
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return CustomUsernamePasswordAuthenticationToken.class.equals(authentication);
    }

    public void setUserDetailsService(CustomUserDetailsService userDetailsService) {
		this.userDetailsService = userDetailsService;
	}
   	
}

UserDetails (spring-security-docs 5.6.2 API)

4.CustomUsernamePasswordAuthenticationFilte.java