본문 바로가기

프로그래밍/Spring

[Spring] Spring Security 5.7.0 이상 Config, desprecated

Spring Boot 3.0 이상 부터는 Spring Security 6.0 이상 버전이 적용된다.

 

이 전 버전들고 동일하게 SecurityConfig를 작성하고 나니 desprecated 된 (더 이상 사용하지 않는)함수들이 많아서 기록 하고자 함

 

  • extends WebSecurtyConfigurerAdapter -> SecurityFilterChain @Bean 등록
  • 람다식 사용
  • EnableGlobalMethodSecurity -> EnableMethodSecurity
  • authorizeRequests -> authorizeHttpRequests
  • access("hasAnyRole('ROLE_ADMIN', 'ROLE_MANAGER')") -> .hasAnyRole("ADMIN", "MANAGER")
  • anyMatchers -> requestMatchers
@Configuration
@EnableWebSecurity
@EnableMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {

        return httpSecurity
                .csrf(csrf -> csrf.disable())
                .authorizeHttpRequests(authorizeRequests -> authorizeRequests
                    .requestMatchers("/user/**").authenticated()
                    .requestMatchers("/manager/**").hasAnyRole("ADMIN", "MANAGER")
                        .requestMatchers("/admin/**").hasRole("ADMIN")
                        .anyRequest().permitAll())
                .formLogin(formLogin -> formLogin
                        .loginPage("/login")
                        .loginProcessingUrl("/login")
                        .defaultSuccessUrl("/"))
                .build();
    }

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