Spring-Security-Filters
, User-defined-Filters
, HandlerInterceptor
let me put these 3 in other way
Filters: Spring-Security-Filters
and User-defined-Filters
Mechanism after DispatherServlet: HandlerInterceptor
(as shown in below pic)

As HandlerInterceptor
comes after DispatcherServlet
, As filters are always processed before reaching servlet confidently i can tell HandlerInterceptor
comes last.
Now order of Spring-Security-Filters
vs User-defined-Filters
If you use traditional spring-mvc (not spring boot) where you can use xml or java based configuration. You can achieve any order for user defined filter. Either you can place after spring security(springSecurityFilterChain) or before as given below.
<filter>
<filter-name>sessionLastAccessTimeUpdateFilter</filter-name>
<filter-class>com.pvn.mvctiles.configuration.SessionLastAccessTimeUpdateFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>sessionLastAccessTimeUpdateFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Here in above example sessionLastAccessTimeUpdateFilter order is before springSecurityFilterChain sessionLastAccessTimeUpdateFilter executes first. You can change order if you need. The equivalent java configuration is given below.
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer
{
@Override
public void onStartup(ServletContext servletContext) throws ServletException
{
super.onStartup(servletContext);
servletContext.addFilter("sessionLastAccessTimeUpdateFilter", new SessionLastAccessTimeUpdateFilter())
.addMappingForUrlPatterns(null, true, "/*");
servletContext.addFilter("springSecurityFilterChain", new DelegatingFilterProxy("springSecurityFilterChain"))
.addMappingForUrlPatterns(null, true, "/*");
}
}
But spring boot is different and imposes lot of restrictions compared to traditional spring approach. Spring boot will not support web.xml and filter registration is allowed only through FilterRegistrationBean
but here registered filters comes after FilterChainProxy
.
But spring security has provided provision to add filter in between spring security filters through .addFilterBefore()
and .addFilterAfter()
Note that spring security has many proxy filters or spring managed beans those filters have specific order. If you implement a filter by creating sub class for UsernamePasswordAuthenticationFilter
then that custom filter order will be same as order defined for UsernamePasswordAuthenticationFilter
Finally, HandlerInterceptor mechanism comes last, but spring security filters and user defined filters can come in any order and it depends on your configuration.
To have rough idea of these filters execution you can refer my answer