Summary
- Spring Security’s Servlet support is based on Servlet Filter.
- A
Filtercan prevent a downstreamFilterorServletfrom being invoked by aFilterChaininstance. - A
Filtercan modify theHttpServletRequestandHttpServletResponsebefore they are used by a downstreamFilterorServlet. - Spring uses
DelegatingFilterProxyto integrate Servlet filter chain with spring framework’sApplicationContext. DelegatingFilterProxydelegates all the works to the spring Beans that implementsFilter.- Spring Security’s Servlet support is provided by the
FilterChainProxy. FilterChainProxyis a Bean, which means it is wrapped with theDelegatingFilterProxy.- The
SecurityFilterChainis used byFilterChainProxyto determine whichFilterBean should be invoked for the current request. SecurityFilterChains are indepenent of each other.- Security Filters has specific order to be invoked. You can check the exact order in the FilterOrderRegistration code.
- To see the log of Security Filter’s invokation, set following properties in
application.properites:logging.level.org.springframework.security=TRACE - Most of the time, defualt Security Filters are enough to serve security interests. But, if publishing custom
FilterintoSecurityFilterChainis needed, use#addFilterBefore(Filter, Class<?>),#addFilterAfter(Filter, Class<?>),#addFilterAt(Filter, Class<?>)ofHttpSecurityto insert or replace custom Filters into specific place. - To determine the location of custom filter, take a look at these following events:
SecurityContextis loaded from the session- Request is protected from common exploits; secure headers, CORS, CSRF
- Request is authenticated
- Request is authorized
- If you want to add custom authenetication filter, place it after
LogoutFilter. - The other recommanded insertion points are described here.
- Instead of extending
Filterand registering it into Security Filter Chain, you can extendOncePerRequestFilteras a Spring Bean. This ensures that the filter will be invoked once per every request. - Custom Security Filters should not be a Spring Bean since it will automatically be registered into Servlet Filter Chain. However, if you really need to make it as a Spring Bean, check here to see how to prevent them from being registered automatically.
ExceptionTranslationFilteris inserted into theSecurityFilterChainas one of the Securit Filters.- It invokes downstream filter first. If an exception occurs, it translate the exception into proper HTTP response (redirect to the login page or return error response).
- To re-request the previous on after user is authenticated, Spring Security uses
RequestCacheto store previous request. - You can customize
RequestCachewhen to store request or not. - If there’s store cache in
RequestCacheinstance,RequestCacheAwareFilterreplay the original request.