Spring Security provides a number of filters by default and mostly they are enough.
But sometimes it’s necessary to implement new functionality with create a new filter to use in the chain.
Filters in spring security are a layer which is used to filter the requests coming from client requesting access to the resources in the server.
So the layer is between the client and the back end resources.
Let’s take a look into the diagram showing the flow.

What is the flow?
Client sends the http request to the server. It is intercepted by the filter to do the authentication and the authorization. We can configure the filter to intercept all requests or selected requests.
If the authorization or authentication fails, then send the response back to client. If it succeeds, then forward the http request to the controller for furher processing.
The above diagram shows a filter chain of 2 filters intercepting requests. But as per the requirement, we can have multiple filter chains which would be intercepting specific kind of requests.
For example, the url hrms/manager/*.jsp can be handled by one filter chain and the url hrms/ceo/*.jsp can be handled by another filter chain.
Let’s look at the Java configuration of an Spring Security Filter.
@Configuration
public class CustomFilterExample
extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterAfter(
new CustomFilter(), BasicAuthenticationFilter.class);
}
}
It extends the WebSecurityConfigurerAdapter class and overrides the configure method.
Let’s implement a filter where we want to allow to access any URL having Role as “USER”.
@Configuration
public class CustomFilterExample
extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/**").hasRole("USER");
}
}
Now let's take another case where we want to allow everyone to access the login page.
@Configuration
public class CustomFilterExample
extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.
authorizeRequests().antMatchers("/login*").permitAll();
.anyRequest().authenticated();
}
}
Imp terms:
-> authorizeRequests() Allows restricting access based upon the HttpServletRequest using RequestMatcher implementations.
-> permitAll() This will allow the public access that is anyone can access endpoint login without authentication.
-> anyRequest().authenticated() will restrict the access for any other endpoint other than login, and the user must be authenticated.
Hope filters are clear!!!!