본문 바로가기
개발 언어별 에러 정리/Spring boot

WebSecurityConfigurerAdapter deprecated 이슈 해결

by sang-rak 2023. 9. 6.
반응형

Spring Security 5.70 이후부터 WebSecurityConfigurerAdapter를 상속 받는 방식은 deprecated 되어 

WebSecurityConfigurerAdapter 상속을 지우고 SecurityFilterChain를 사용하여야 한다.

공식문서를 참조 하여 코드 작성을 하면 된다.

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

 

Spring Security without the WebSecurityConfigurerAdapter

In Spring Security 5.7.0-M2 we deprecated the WebSecurityConfigurerAdapter, as we encourage users to move towards a component-based security configuration. To assist with the transition to this new style of configuration, we have compiled a list of common

spring.io

 

AuthenticationManager 커스텀 사용 시 

로컬 Authentication Manager 액세스
로컬 Authentication Manager는 사용자 지정 DSL에서 액세스할 수 있습니다.

이는 실제로 Spring Security가 내부적으로 HttpSecurity.authorizeRequests()와 같은 메서드를 구현하는 방법입니다.

 

사용예시 

package api.jackdang.config;
import api.jackdang.config.jwt.JwtAuthenticationFilter;
import api.jackdang.config.jwt.JwtAuthorizationFilter;
import api.jackdang.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

/**
 * spring security
 */
@Configuration
@EnableWebSecurity // Spring Security 설정 클래스
public class SecurityConfig {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private CorsConfig corsConfig;

    /*
     비밀번호 암호화
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        // 비밀번호를 DB에 저장하기 전 사용할 암호화
        return new BCryptPasswordEncoder();
    }
    /*
    authenticationManager 사용시 config 세팅 필요
    */
    @Bean
    protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http
                .csrf().disable()// JWT 인증
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 세션 사용 X
                .and()
                .formLogin().disable()
                .httpBasic().disable()
                .apply(new MyCustomDsl()) // 커스텀 필터 등록
                .and()
                .authorizeRequests(authroize -> authroize
                .antMatchers("/api/v1/admin/**")//.hasRole("ROLE_ADMIN")
                    .access("hasRole('ROLE_MANAGER') or hasRole('ROLE_ADMIN')")
                .antMatchers("/api/v1/user/**")  //.hasRole("ROLE_USER")
                    .access("hasRole('ROLE_USER') or hasRole('ROLE_MANAGER') or hasRole('ROLE_ADMIN')")
                .antMatchers("/api/v1/auth/**").permitAll()  // 인증절차 없이 허용
                    .anyRequest().permitAll())
                .build();
    }

    public class MyCustomDsl extends AbstractHttpConfigurer<MyCustomDsl, HttpSecurity> {
        @Override
        public void configure(HttpSecurity http) throws Exception {
            AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManager.class);
            http
                    .addFilter(corsConfig.corsFilter())
                    .addFilter(new JwtAuthenticationFilter(authenticationManager))
                    .addFilter(new JwtAuthorizationFilter(authenticationManager, userRepository));
        }
    }





}
반응형

댓글