1. Overview
In this article, we will learn to create a custom Security filter with an example.
2. Spring Security
Spring Security’s web infrastructure is based entirely on standard servlet filters.
The Spring container maintains a filter chain internally where each of the filters has a particular responsibility and filters are added or removed from the configuration depending on which services are required.
Apart from these default filters, you can also configure a custom filter to fit your use case.
2.1. Security Filter
The Servlet filters intercept the requests from the client before it reaches the target resource (e.g. Controller, Servlet, JSP, HTML files, static content, so on) in a web application and can also post-process the responses before sending them to the clients.
You can create security filters by implementing the Filter interface from the javax.servlet
package. This Filter interface provides the doFilter()
method which you can override to add your custom logic.
You can add the custom filter before or after an existing filter in the security filter chain and even can replace one.
3. Custom Security Filter example
Now let’s see a simple example where you prevent processing certain URLs.
In the below scenario, we have created a CustomFilter
class, an implementation of the Filter
interface. You can also extend generic base class implementations available in the Spring boot web.filter package.
We have overridden the doFilter
class and written logic to prevent processing the URIs with /delete
path. We configured to throw 403 error whenever the user hits the URI with “delete”.
package filters; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class CustomFilter implements Filter { private Logger logger = LoggerFactory.getLogger(CustomFilter.class.getName()); @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; if (!request.getRequestURI().contains("delete")) { filterChain.doFilter(servletRequest, servletResponse); } else { logger.error("Delete not supported"); response.setStatus(HttpServletResponse.SC_FORBIDDEN); } } }
3.1 Configure Custom Filter With Spring Security
Now let’s configure our custom filter with the Spring Security filter chain. You can use any of the following ways to append our custom Filter.
- addFilterAfter(filter, class) – Adds after the position of the specified filter class.
- addFilterBefore(filter, class) – Adds before the position of the specified filter class.
- addFilterAt(filter, class) – Adds a filter at the location of the specified filter class.
- addFilter(filter) – Adds a filter that must be an instance of or extend the filter provided by Spring Security
Here, we are adding the custom filter after the BasicAuthenticationFilter
filter in the filter chain. You can add before / after any filter in the filter chain.
package com.tedblob.customfilter; import filters.CustomFilter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; @Configuration public class CustomAdapter extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.addFilterAfter( new CustomFilter(), BasicAuthenticationFilter.class); } }
3.2. Run the application
If you run the application and hit the URL http://localhost:8080/delete
, the custom filter intercepts and blocks the processing of the request. It then throws 403 error.
4. Conclusion
To sum up, we have learned to create a custom security filter in a Spring boot application with a relevant example.