본문 바로가기
개발 및 잡담/JAVA

[JAVA] SpringSecurity 에서 WebSecurityConfigurerAdapter의 extends가 안될 때 (부제: 스프링 시큐리티 POST, GET 제외 차단)

by 아는게 없어 항상 몰라 2023. 8. 25.
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/url/**") // 차단하려는 URL 패턴
            .denyAll() // 모든 접근 차단
            .and()
            .csrf()
                .disable(); // CSRF 보안 비활성화
    }
}​

 

 

이런 식으로 /url/** 패턴에 대해 모든 접근을 차단을 시키려고 했는데  extends WebSecurityConfigurerAdapter 부분에 자꾸 빨간줄이 그어졌다. 이유는 5.7 버전 이상의 시큐리티부턴 사용을 권장하지 않는다며 지원을 안하는 듯하다.

 

 

 

해결 방법은 bean으로 등록하기

 
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        
    	http
    	.authorizeHttpRequests() 
            .requestMatchers("/url/**")
            .denyAll()
        .and()
        .csrf()
            .disable()
            
        return http.build();
    }

 

 

요런 느낌으로 

 

 

이것을 응용하여

 

만약 "모든 패턴에 대하여 POST와 GET만 허용하고 나머지 접근은 차단"하고 싶다면 아래처럼 작성하면 된다

@Configuration
@EnableWebSecurity
public class SecurityConfig {
	
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        
    	http
    	.authorizeHttpRequests() 
            .requestMatchers(HttpMethod.GET, "/**")
            .permitAll()
            .requestMatchers(HttpMethod.POST, "/**")
            .permitAll()
            .anyRequest().denyAll()
        .and()
        .csrf()
            .disable();

        return http.build();
    }

}

댓글