Java Spring Boot here. I am building a RESTful web service that uses Spring Security for authentication/authorization.
Spring Security ships with a vast array of its own flexible and configurable Filters. My service has a need to define several of its own Filters, however:
- they have absolutely nothing to do with security, and as such, shouldn't require any configuration within Spring Security's API; and
- I do want them to be invoked after Spring Security has already allowed requests through all of its own security Filters; meaning these "non-security" Filters only get invoked if Spring Security has allowed the request through, ahead of time
I see this answer as well as this one but these both involve configuring other custom security Filters to work with Spring Security's built-in Filters. How can I configure Spring Boot to "position" my non-security Filters "after" (further down the filter chain) from Spring Security? And how can I control the order of those Filters once I do?
CodePudding user response:
You may set order of filter using @Order annotation. It has default value Integer.MAX_VALUE
this way your filter will be executed last(lower values have higher priority). Here is an example:
@Order
@Component
public class TestFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
filterChain.doFilter(servletRequest, servletResponse);
}
}
Spring Security is a single physical Filter
but delegates processing to a chain of internal filters such as: SecurityContextPersistenceFilter, RememberMeAuthenticationFilter, AnonymousAuthenticationFilter, etc. The security filter is installed at a position defined by SecurityProperties.DEFAULT_FILTER_ORDER which is set to -100
. So any filter with order higher than -100
will be executed after FilterChainProxy (concrete class of spring security filter)
For example:
@Order(SecurityProperties.DEFAULT_FILTER_ORDER-1)
@Component
public class BeforeSecurityFilter implements Filter
Will be executed before security filter and:
@Order(SecurityProperties.DEFAULT_FILTER_ORDER 1)
@Component
public class AfterSecurityFilter implements Filter
Will be executed after security filter