본문 바로가기
Spring

[spring] WebSecurityConfigurerAdapter Deprecated 해결

by 초이사 2023. 6. 20.

지금 하는 프로젝트에서 원래는 WebSecurityConfigurerAdapter를 상속받아서 스프링시큐리티를 사용할 계획이었는데,

WebSecurityConfigurerAdapter Deprecated가 되었다고 나와서 변경할 필요가 있었다.

 

스프링 시큐리티 5.7( 스프링 부트 2.7.x 이후부터는 모두 5.7을 기본 포함)부터는 WebSecurityConfigurerAdapter 대신 SecurityFilterChain 빈을 주입하는 방식으로 변경되었다고 한다.

 

변경전

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    public static PasswordEncoder getPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().disable()
                .csrf().disable()
                .formLogin().disable()
                .headers().frameOptions().disable();
    }
}

 

변경후

WebSecurityConfigurerAdapter 상속을 없애고 configure() 메서드의 반환형식을 SecurityFilterChain으로 바꾼다음 bean 한다.

@Configuration
@EnableWebSecurity
public class WebSecurityConfig{
    @Bean
    public static PasswordEncoder getPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain configure(HttpSecurity http) throws Exception {
        http.cors().disable()
                .csrf().disable()
                .formLogin().disable()
                .headers().frameOptions().disable();

        return http.build();
    }
}

 

바꿔주고 전체 테스트를 하니 controller 테스트만 모두 실패했다. 200이 나와야 하는데, 401 또는 403 에러가 발생하면서 실패되었다.

controller테스트 실패

 

 

원인

controller테스트를 @WebMvcTest를 사용해서 진행했었는데, 스프링 팀에서는 모든 사람들이 스프링 시큐리티를 사용하지는 않기 때문에 @WebMvcTest에 @EnableWebSecurity를 포함하지 않도록 했다고 한다.

참고 (https://github.com/spring-projects/spring-boot/issues/31162)

 

그래서 @WebMvcTest가 WebSecurityConfigurerAdapter에 대한 설정 파일은 읽어오지만 @EnableWebSecurity만 달려있는 파일은 읽어오지 못해서 발생한 문제였다.

 

 

해결

@WebMvcTest를 하는 곳에 @ImportAutoConfiguration(WebSecurityConfig.class)를 작성해서 @WebMvcTest가 파일을 읽어올 수 있도록 해주어야 한다. 그렇게 하고 전체 테스트를 돌려보니 테스트가 모두 통과했다!!

전체 테스트 통과

 

 

 

 

참고

 

 

 

댓글