티스토리 뷰

728x90
반응형

AuthenticationProvider를 구현함으로써 인증 공급자를 재구성할 수 있다.

package com.example.demo.config;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

	private final UserDetailsService userDetailsService;
    private final PasswordEncoder passwordEncoder;

    public CustomAuthenticationProvider(UserDetailsService userDetailsService, PasswordEncoder passwordEncoder) {
        this.userDetailsService = userDetailsService;
        this.passwordEncoder = passwordEncoder;
    }
    
	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		String userName = authentication.getName();
		String userPassword = String.valueOf(authentication.getCredentials());
		UserDetails userDetails = this.userDetailsService.loadUserByUsername(userName);
		
		if(this.passwordEncoder.matches(userPassword, userDetails.getPassword())) {
			return new UsernamePasswordAuthenticationToken(userName, userPassword, userDetails.getAuthorities());
        } else {
            throw new BadCredentialsException("Invalid username or password");
        }
	}
 
	@Override
	public boolean supports(Class<?> authentication) {
		return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
	}

}

AuthenticationProvider를 구현한 "CustomAuthenticationProvider"를 스프링 시큐리티에 추가한다.

package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig {
	
	@Bean
	UserDetailsService userDetailsService() {
		var userDetailsService = new InMemoryUserDetailsManager();
		
		var user = User.withUsername("james")
				.password(passwordEncoder().encode("12345"))
				.authorities("auth_name")
				.build();
		
		userDetailsService.createUser(user);
		return userDetailsService;
	}
	
	@Bean
	PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}
	
	@Bean
	SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
		http
			.httpBasic(Customizer.withDefaults()) // HTTP Basic 인증 활성화
			.authorizeHttpRequests(authorize -> authorize
				//.anyRequest().permitAll() // 인증 없이 접근 가능
				//.requestMatchers("/hi").permitAll() // "/hi"만 인증 없이 접근 가능
				.anyRequest().authenticated() // 인증 필수("/hi"는 제외)
			);
		
		return http.build();
	}
	
	@Bean
	CustomAuthenticationProvider customAuthenticationProvider(UserDetailsService userDetailsService, PasswordEncoder passwordEncoder) {
		return new CustomAuthenticationProvider(userDetailsService, passwordEncoder);
	}

}
728x90
반응형