Summary
- Spring Security’s Servlet support is based on Servlet Filter.
- A
Filter
can prevent a downstreamFilter
orServlet
from being invoked by aFilterChain
instance. - A
Filter
can modify theHttpServletRequest
andHttpServletResponse
before they are used by a downstreamFilter
orServlet
. - Spring uses
DelegatingFilterProxy
to integrate Servlet filter chain with spring framework’sApplicationContext
. DelegatingFilterProxy
delegates all the works to the spring Beans that implementsFilter
.- Spring Security’s Servlet support is provided by the
FilterChainProxy
. FilterChainProxy
is a Bean, which means it is wrapped with theDelegatingFilterProxy
.- The
SecurityFilterChain
is used byFilterChainProxy
to determine whichFilter
Bean should be invoked for the current request. SecurityFilterChain
s 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
Filter
intoSecurityFilterChain
is needed, use#addFilterBefore(Filter, Class<?>)
,#addFilterAfter(Filter, Class<?>)
,#addFilterAt(Filter, Class<?>)
ofHttpSecurity
to insert or replace custom Filters into specific place. - To determine the location of custom filter, take a look at these following events:
SecurityContext
is 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
Filter
and registering it into Security Filter Chain, you can extendOncePerRequestFilter
as 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.
ExceptionTranslationFilter
is inserted into theSecurityFilterChain
as 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
RequestCache
to store previous request. - You can customize
RequestCache
when to store request or not. - If there’s store cache in
RequestCache
instance,RequestCacheAwareFilter
replay the original request.