Spring Security is developed on top of the Spring Framework and uses the filters concept in the Servlet engine. Filters are like Servlet; they come into action when any request comes to Servlet and can decide whether the request should be forwarded to Servlet or not. Spring Security registers a single javax.servlet.Filter
, that is, the DelegatingFilterProxy
.
Before starting with Spring Security, let's quickly recall what Servlet filters are. In the following figure, a user enters the URL in the browser. The request comes to the container and then to Servlet after referring to web.xml
for Servlet mapping with respecting URL. After processing the request, the request goes back to the user.
A Filter is present between Servlet and Container. It intercepts the requests and responses to and from Servlet and can pre-process and post-process, as shown in the following diagram:
In the web.xml
file, you'll find the following code:
<filter> <filter-name>filterA</filter-name> <filter-class>FilterA</filter-class> </filter> <filter-mapping> <filter-name>filterA</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
In the preceding code snippet, we have mapped filterA
to all URLs. Now, in the FilterA.java
class, you'll find the following code:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) { // do something before filter System.out.println("Starting Filter"); // run rest of the application filterChain.doFilter(request, response); // cleanup System.out.println("Ending Filter"); }
Now, we have the code for FilterA
. First, it invokes a message before the rest of the applications run. Then, it runs the rest of the application. Lastly, it prints a message again. From the following diagram, let's understand how requests gets impacted by this filter:
As shown in the preceding diagram, when we make a request to our application using HTTP GET /home
URL, the Servlet container recognizes the filterA
intercepts this URL. The container invokes the doFilter()
method of the FilterA
class. As soon as the doFilter()
method is invoked, it prints the message Starting Filter
. Then, filterA
invokes the filterChain
, and then home.jsp
is invoked. Next, it returns to the filterChain
.
Filters can be used for the following operations:
Spring Security is dependent on this filter mechanism. So, before reaching out to Servlet to perform some business logic, some security can be performed using the filters.