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:
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?
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