오늘 이거 알았네요/Java

[Spring] SecurityFilterChain 사용하기 (security6)

로그관리자 2023. 1. 31. 15:10
728x90

 

 

 

 

🚑 원인

 

스프링 시큐리티 5.7x 부터 WebSecurityConfigurerAdapter가 deprecated 되었다.  

 

 

 

 

 

 

https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter

 

공식 블로그에 따르면

SecurityFilterChainWebSecurityCustomizer를 빈으로 등록해 사용하는 방식을 권장한다. 

 

Security Filter ?

더보기

스프링 시큐리티 bean은 필터로 구성되어 있고 이 필터들의 모음을 SecurityFilterChain.

필터는 각각 고유한 역할을 담당하며 default로 등록되는 필터가 존재한다.

 

 

 

@Configuration
public class SecurityConfiguration {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests((authz) -> authz
                .anyRequest().authenticated()
            )
            .httpBasic(withDefaults());
        return http.build();
    }
 
    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.ignoring().antMatchers("/ignore1", "/ignore2");
    }

}

 

 

 

 

또한 security6 부터는 

mvcMatchers나 antMatchers 가 deprecated 되었으므로  requestMatchers를 사용한다 .

 

 

https://docs.spring.io/spring-security/reference/whats-new.html

 

 

 

 

잠깐

antMatchers 와 mvcMatchers 의 차이를 알아보자 

 

더보기

 

특정 경로를 지정해서 권한을 설정할 때 사용

 

예를 들어 (”/info”) 한다면 

antMatchers : /info          정확한 URL만

mvcMatchers : /info, /info.html, /info.xyz 등 다양하게 일치

 

 

 

 

 

 

🚑 해결 

 

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
                http.authorizeHttpRequests()
                .requestMatchers("/", "/login", "/sign-up", "/check-email", "/check-email-token",
                        "/email-login", "/check-email-login", "login-link", "/profile/*").permitAll() 
                .requestMatchers(HttpMethod.GET, "/profile/*").permitAll() 
                .anyRequest().authenticated();   
        
                return http.build();
    }

    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.ignoring()
                .requestMatchers("/node_modules/**")
                .requestMatchers(PathRequest.toStaticResources().atCommonLocations());
    }
}

 

 

 

 

그리고 security 6 버전은 JDK 17부터 가능하다. 

 

 

 

 

 

 

 

 

 

 

 

참고

https://stackoverflow.com/questions/74683225/updating-to-spring-security-6-0-replacing-removed-and-deprecated-functionality

 

 

 

 

 

 

 

 

728x90