DelegatingFilterProxy ,springSecurityFilterChain ,ContextLoaderListener and FilterChainProxy

When you need to configure Spring Security or you need to solve a problem that related to Spring Security, for example the Spring Security: No ContextLoaderListener registered. You need to know something about Spring Security as listed here

DelegatingFilterProxy

First of all, DelegatingFilterProxy is a Servlet filter, a filter provided by Spring Framework. To know more about Servlet filter in general:How servlet filter works.

As the name indicated, its a proxy filter, it act as a filter, but it don't do the actual work, what it do is delegate the filtering to others. How it does this? By looking for a bean, and then find the instance with the Spring bean facility. And hand over to the bean. The bean must implements the Filter interface.

springSecurityFilterChain and FilterChainProxy

The bean name can be anything you created, but if its about Spring Security, you use the default one.

Spring Security creates a FilterChainProxy bean named "springSecurityFilterChain" which maintains the stack of security filters which make up the web security configuration.The FilterChainProxy is a single filter that chains together multiple additional filters. These filters, along with the FilterChainProxy, are created by Spring based on the security configuration. And what we need to do in DelegatingFilterProxy is to delegate to it.

So if you are configuring Spring Security, you should use bean name "springSecurityFilterChain" when adding DelegatingFilterProxy. The bean has type FilterChainProxy. This is still a proxy, but its not a Servlet filter, its what the Servlet filter delegate to.

Here is how the DelegatingFilterProxy is added in Spring Security

 
        String filterName = DEFAULT_FILTER_NAME; // the string value is "springSecurityFilterChain"
        DelegatingFilterProxy springSecurityFilterChain = new DelegatingFilterProxy(filterName);
        registerFilter(servletContext, true, filterName, springSecurityFilterChain);
 

Notice here, the filter name and bean name both the "springSecurityFilterChain".

The filter name here is the bean name.

The bean configuration will looks like this

 
<beans:bean id="springSecurityFilterChain" class="org.springframework.security.web.FilterChainProxy">
 

ContextLoaderListener

ContextLoaderListener is a bootstrap listener. It start up and shut down Spring's root WebApplicationContext.

ContextLoaderListener is optional, you can run a Spring application with only Dispatcher Servlet configured, but for Spring Security, you need one.

The context of DispatcherServlet is dedicated for MVC related beans like controllers, views, handlers. Its not include security related beans, to use Spring Security, you must put security related beans in root application context, thus you need to configure ContextLoaderListener.