본문 바로가기
공부/java & Spring

[Spring security] The type WebSecurityConfigurerAdapter is deprecated

by 고기 2023. 6. 28.

Spring security를 적용하기 위해 환경설정 파일을 작성하고 있는데 역시나 에러가 나왔다...

사실 예전 문법을 사용해서 발생한 거라 공식문서를 보면서 만들었으면 된거였는데...

 

문제는 WebSecurityConfigurerAdapter 이놈이다.

스프링 버전이 최신이라면 WebSecurityConfigurerAdapter는 더 이상 사용하지 않기 때문에 에러가 남!

이건 내가 직접 작성한 코드는 아니고 chat gpt를 사용해서 만든 테스트 코드다.

// SecurityConfig.java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/admin").hasRole("ADMIN")
                .antMatchers("/user").hasAnyRole("USER", "ADMIN")
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .and()
            .logout()
                .and()
            .csrf().disable();
    }
}

 

지피티 선생님에게 여쭤봤더니 그렇다네.

 

아무튼 WebSecurityConfigurerAdapter대신 SecurityFilterChain를 사용하면 된다!

//The type WebSecurityConfigurerAdapter is deprecated
@Configuration
@EnableWebSecurity(debug = true)
public class SecurityConfig {

    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/admin").hasRole("ADMIN")
                .antMatchers("/user").hasAnyRole("USER", "ADMIN")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .logout()
                .and()
                .csrf().disable();

        return http.build();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration)
            throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

}

 

참고하자!

https://stackoverflow.com/questions/72381114/spring-security-upgrading-the-deprecated-websecurityconfigureradapter-in-spring

 

Spring Security: Upgrading the deprecated WebSecurityConfigurerAdapter in Spring Boot 2.7.0

I am trying to update the WebSecurityConfigurerAdapter as it has been deprecated. The class is configured as follows: @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = ...

stackoverflow.com

 

댓글