[Spring]

[Spring Security] WebSecurityConfigurerAdapter Deprecated 해결

danhan 2023. 1. 18. 18:05

더이상 WebSecurityConfigurerAdapter를 지원하지 않는다.

spring 공식문서에 가보니 Spring Security 5.7.0-M2 부터는 구성 요소 기반 보안 설정으로 변경된다는 이슈가 있었다.

WebSecurityConfigurerAdapter 상속 후, configure 메소드를 오버라이딩 하여 설정하는 방식에서 SecurityFilterChain를 빈으로 등록하는 방식으로 변경했다고 한다.

// 이전 방식
// WebSecurityConfigurerAdapter 상속 후, configure 메소드 오버라이딩
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests()
.antMatchers("/user/**").authenticated()
.antMatchers("/manager/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_MANAGER')")
.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
.anyRequest().permitAll();
}
}
// 현재 방식
// SecurityFilterChain를 빈으로 등록
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests()
.antMatchers("/user/**").authenticated()
.antMatchers("/manager/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_MANAGER')")
.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
.anyRequest().permitAll();
}
}

추가로 authorizeRequests, antMatcher, hasRole도 더이상 지원하지 않기 때문에 각각 authorizeHttpRequest, requestmatchers, hasAnyAuthority로 바꾸어 사용한다.

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeHttpRequests()
.requestMatchers("/user/**").authenticated()
.requestMatchers("/manager/**").hasAnyAuthority("ROLE_ADMIN", "ROLE_MANAGER")
.requestMatchers("/admin/**").hasAuthority("ROLE_ADMIN")
.anyRequest().permitAll();
return null;
}

여기까지 했으면 localhost:8080로 접속해 원하는 페이지로 연결되는지 확인해보자.

/user, /manager, /admin이 아닌 url은 permitAll()을 해주었기 때문에 시큐리티의 login 페이지가 아닌 원래 페이지가 나와야한다.

 

그런데 여전히 localhost:8080으로 localhost:8080/login으로 연결된다.

.anyRequest().permitAll();이 제대로 동작하지 않는다. 
.anyRequest() 대신 .requestMatchers("/**")로 바꿔주었다.

@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeHttpRequests()
.requestMatchers("/user/**").authenticated()
.requestMatchers("/manager/**").hasAnyAuthority("ROLE_ADMIN", "ROLE_MANAGER")
.requestMatchers("/admin/**").hasAuthority("ROLE_ADMIN")
.requestMatchers("/**").permitAll();
return http.build();
}
}

 

참고