Back End/서버 비용

[Spring Security] Filter 가 두번 실행될 때 (when filter get executed twice in Spring)

DevPing9_ 2022. 12. 17. 15:07

 

Case

갑자기 내가 작성한 AuthenticationFilter 가 2번 실행되는 현상을 목격했다.
단순히 chain.doFilter() 를 기준으로 앞뒤로 실행되는 것이 아닌 정확히 모든 로직이 2번이 실행되는 것이다.

 

Cause

원인은 아래 예제코드와 같이 Spirng Security 에 등록할 필터를 Bean 으로 등록하고, 
Security Config 에서 또 Filter 를 추가한 데 있었다.
@Configuration
@EnableWebSecurity(debug = false)
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
class SecurityConfig {

    @Bean
    fun filterChain(
        authenticationService: AuthenticationService,
        userAuthenticationFilter: AuthenticationFilter
    	....
    ): SecurityFilterChain {
        http.
            ....
            .addFilterAt(userAuthenticationFilter, UsernamePasswordAuthenticationFilter::class.java)

        return http.build()
    }

    
    @Bean
    fun userAuthenticationFilter(authenticationService: AuthenticationService): AuthenticationFilter {
        return MyAuthenticationFilter(
            AntPathRequestMatcher(LOGIN_URL, "POST"),
            ProviderManager(AuthProvider(authenticationService))
        )
    }
}

 

반환형이 AuthenticationFilter 인 Bean 으로 등록됨에 따라
이미 Spring 에서 Filter 로 인식하고 추가를 했는데,
명시적으로 Spring Security Filter Chain 에 추가를 한번 더 함으로써 2번 동작하게 되었던 것이다.

 

Resolution

Bean 등록을 해제하여 중복을 제거한다.
@Configuration
@EnableWebSecurity(debug = false)
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
class SecurityConfig {

    @Bean
    fun filterChain(
        authenticationService: AuthenticationService,
    	....
    ): SecurityFilterChain {
        http.
            ....
            .addFilterAt(userAuthenticationFilter(authenticationService), UsernamePasswordAuthenticationFilter::class.java)

        return http.build()
    }


    fun userAuthenticationFilter(authenticationService: AuthenticationService): AuthenticationFilter {
        return MyAuthenticationFilter(
            AntPathRequestMatcher(LOGIN_URL, "POST"),
            ProviderManager(AuthProvider(authenticationService))
        )
    }
}

 

 

 


Reference

 

why spring boot filter call twice?

my spring boot version is 1.5.4,here is my config code @SpringBootApplication @Configuration @RestController @ServletComponentScan public class Application { public static void main(String[] ...

stackoverflow.com

 

728x90