I think the spring-boot-security is not consistent with a spring-web in terms of filters
The situation:
I have a common-lib, which contains 2 filters I use across 4 projects I have 3 common services and 1 gateway service with a spring security Filters are annotated with @ Component and @ Order annotations. They are autoregistered in all applications and it is fine. However for the project with a security I want to have a control over the order. (My case: run filters before BasicAuthenticationFilter). It is not possible to do with @ Order annotation. BasicAuthenticationFilter runs always BEFORE custom filters, even if the order of custom filters is negative.
Well then I think, OK, my filters implement OncePerRequestFilter, it means if I register them explicitly in security configuration
http.addFilterBefore(new SwaggerAuthFilter(authService), BasicAuthenticationFilter.class);
then it will override the autoregistered order. However the very strange thing happens, now they are executed twice.
The enhancement I want to suggest is next: Create a transparent config which will accept
(req, resp) -> {
filter1(..
filter2(..
interceptor1(..
interceptor2(..
apiHandler(req, resp)
)
)
)
}
because now the filterchain is a highest class of magic, and it is very hard to understand the entire chain
Comment From: wilkinsona
@oleksandr-skoryi When you use Spring Security, there are two filter chains. There is the main filter chain that is managed by the Servlet container. There is also a secondary, "virtual" filter chain that's managed by Spring Security. It's plugged into the main filter chain as a filter. You can learn more about this in Spring Security's architecture documentation.
Spring Boot automatically add filters that are defined as beans to the main filter chain. If you want your filters to be called as part of Spring Security's filter chain, you probably don't want to define them as beans otherwise they will end up in both filter chains. https://github.com/spring-projects/spring-boot/issues/16500 is tracking some improvements in this area.
If you want your filters to be called as part of the main filter chain before the security filters are called, you can order them to achieve this. The default order of Spring Security's filter is -100 and this can be configured using the spring.security.filter.order property.
Unfortunately, we can't provide a declarative API that allows configuration of the entire filter chain in one place as that one place probably won't know about all of the filters that need to be configured. Thanks, though, for the suggestion.