For the latest stable version, please use Spring Security 6.3.3!
Spring Security’s Servlet support is based on Servlet Filters, so it is helpful to look at the role of Filters generally first. The following image shows the typical layering of the handlers for a single HTTP request.
The client sends a request to the application, and the container creates a FilterChain
, which contains the Filter
instances and Servlet
that should process the HttpServletRequest
, based on the path of the request URI. In a Spring MVC application, the Servlet
is an instance of DispatcherServlet
. At most, one Servlet
can handle a single HttpServletRequest
and HttpServletResponse
. However, more than one Filter
can be used to:
- Prevent downstream
Filter
instances or theServlet
from being invoked. In this case, theFilter
typically writes theHttpServletResponse
.
- Modify the
HttpServletRequest
orHttpServletResponse
used by the downstreamFilter
instances and theServlet
.
The power of the Filter
comes from the FilterChain
that is passed into it.
FilterChain
Usage Example
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
// do something before the rest of the application
chain.doFilter(request, response); // invoke the rest of the application
// do something after the rest of the application
}
Since a Filter
impacts only downstream Filter
instances and the Servlet
, the order in which each Filter
is invoked is extremely important.
Spring provides a Filter
implementation named DelegatingFilterProxy
that allows bridging between the Servlet container’s lifecycle and Spring’s ApplicationContext
. The Servlet container allows registering Filter
instances by using its own standards, but it is not aware of Spring-defined Beans. You can register DelegatingFilterProxy
through the standard Servlet container mechanisms but delegate all the work to a Spring Bean that implements Filter
.