개발 환경
Spring boot: 3.2.1
Spring Security: 6.2.1
문제
Spring Security 6에서 Path마다 FilterChain을 다르게 적용하다가 문제가 발생하였다.
Spring Secuirty는 설정한 filterChain 모두 FilterChainProxy의 filterChains 배열에 모두 저장하고 매 요청마다 getFilters에서 요청 경로와 매칭되는 filterChain을 찾아 적용한다.
내가 겪은 문제는 설정한 FilterChain들은 모두 등록이 되었지만, 모든 FitlerChain의 request Matcher가 any request로 등록이 되어 모든 요청이 첫번째 FilterChain을 사용하는 문제가 발생했다.
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
@Order(1)
public SecurityFilterChain noticeFilterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(authorizationManagerRequestMatcherRegistry ->
authorizationManagerRequestMatcherRegistry
.requestMatchers("/notice").permitAll()
)
.build();
}
@Bean
@Order(2)
public SecurityFilterChain adminFilterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(authorizationManagerRequestMatcherRegistry ->
authorizationManagerRequestMatcherRegistry
.requestMatchers("/admin/**")
.authenticated())
.httpBasic(Customizer.withDefaults())
.build();
}
@Bean
@Order(3)
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(authorizationManagerRequestMatcherRegistry ->
authorizationManagerRequestMatcherRegistry.anyRequest().authenticated())
.formLogin(Customizer.withDefaults())
.build();
}
}
해결법
Path별 FilterChain을 다르게 적용하려면 securityMatcher를 이용해 경로를 지정해줘야한다.
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
@Order(1)
public SecurityFilterChain noticeFilterChain(HttpSecurity http) throws Exception {
return http
.securityMatcher("/notice")
.authorizeHttpRequests(authorizationManagerRequestMatcherRegistry ->
authorizationManagerRequestMatcherRegistry.anyRequest().permitAll()
)
.build();
}
@Bean
@Order(2)
public SecurityFilterChain adminFilterChain(HttpSecurity http) throws Exception {
return http
.securityMatcher("/admin/**")
.authorizeHttpRequests(authorizationManagerRequestMatcherRegistry ->
authorizationManagerRequestMatcherRegistry.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults())
.build();
}
@Bean
@Order(3)
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(authorizationManagerRequestMatcherRegistry ->
authorizationManagerRequestMatcherRegistry.anyRequest().authenticated())
.formLogin(Customizer.withDefaults())
.build();
}
}
참고
https://www.inflearn.com/questions/1068338
https://github.com/spring-projects/spring-security/issues/12950
'Spring > Security' 카테고리의 다른 글
Spring Security WebSecurityConfigurerAdapter 대체하기 (0) | 2023.12.31 |
---|