When I started learning Spring Security, I thought securing a Spring Boot application was as simple as adding one dependency and writing a few annotations.
But then I encountered things like:
- Security Filters
- DispatcherServlet
- FilterChainProxy
- SecurityFilterChain
- Authentication
- Authorization
- CSRF
And suddenly, things became confusing.
One question bothered me the most:
Why does Spring Security execute filters before DispatcherServlet?
I was familiar with Spring MVC, where a request reaches the DispatcherServlet and then gets mapped to a controller.
But Spring Security seemed to work before all of that.
I wanted to understand what happens internally when a user sends an HTTP request to a Spring Boot application.
In this post, we'll start from the request lifecycle and gradually understand how Spring Security protects our application.
We'll also create a custom security configuration using @Configuration, @EnableWebSecurity, and SecurityFilterChain.
Versions used in this post:
- Java 17
- Spring Boot 4.2.0
- Spring Framework 7.1.0
- Spring Security 7.2.0
The examples use Java 17-compatible syntax.
Table of contents
- What problem does Spring Security solve?
- Authentication and authorization are different
- What happens when Spring Security is added
- Understand the servlet filter chain
- What is a servlet filter?
- Why filters run before DispatcherServlet
- Where FilterChainProxy and SecurityFilterChain fit
- Does every request reach the controller?
- Configure Spring Security using Java configuration
- What
@Configurationdoes - What
@EnableWebSecuritydoes - Define a SecurityFilterChain bean
- Understand request matchers and rule order
- What happens to the default security configuration
- What
- Cross site request forgery CSRF
- What is a CSRF attack?
- How Spring Security protects against CSRF
- Should you disable CSRF for a JWT API?
- CSRF is not CORS
- Connect this to your SecurityConfig
- What your current configuration is doing
- Why the complete configuration needs careful choices
- Which one should I use?
- Common mistakes
- Quick recap
- Try it yourself
What problem does Spring Security solve?
Imagine Asha is building an online banking application.
Users should be able to:
- Register an account.
- Log in.
- View their account balance.
- Transfer money.
- View their transaction history.
Now consider two situations.
Situation 1:
A user who hasn't logged in tries to access their account balance.
Should the application allow it?
Obviously not.
Situation 2:
A normal user logs in successfully and tries to access an administrator's dashboard.
Should the application allow it?
Again, no.
These are two different security problems.
Spring Security helps us handle both.
It is a framework that provides authentication, authorization, and protection against common web application attacks.
Authentication and authorization are different
These two terms are frequently confused by beginners.
Let's understand them separately.
Authentication: Who are you?
Authentication verifies the identity of a user.
For example:
Asha enters:
Username: asha Password: asha123 The application checks whether these credentials are valid.
If they are valid, Asha is authenticated.
Authorization: What are you allowed to do?
Authorization determines what an authenticated user is permitted to access.
For example:
Asha | +-- Role: USER | +-- View Profile ALLOWED +-- View Transactions ALLOWED +-- Admin Dashboard DENIED Another user might have:
Ravi | +-- Role: ADMIN | +-- View Profile ALLOWED +-- View Transactions ALLOWED +-- Admin Dashboard ALLOWED Notice the difference.
Authentication answers:
"Are you really Asha?"
Authorization answers:
"Is Asha allowed to access this resource?"
Behind the scenes
HTTP REQUEST | v AUTHENTICATION | v Verify User Credentials | +-----+-----+ | | Valid Invalid | | v v Authenticated Reject | v AUTHORIZATION | v Check Permissions | +---+---+ | | Allowed Denied | | v v Continue 403 Spring Security provides infrastructure to handle both operations.
What happens when Spring Security is added
Let's understand what happens when we add Spring Security to a Spring Boot application.
First, add the dependency:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> That's enough to bring Spring Security into a typical Spring Boot application.
Now start your application.
What happens?
By default, Spring Boot's security auto-configuration secures HTTP requests.
It provides default authentication behaviour, including a generated login page and a default user configuration when no custom authentication setup is provided.
You might see a generated password in your application startup logs.
For example:
Using generated security password: <generated-password> The exact password will be different in your application.
Now try accessing any endpoint.
Instead of directly receiving the response, an unauthenticated browser request will generally be redirected to the login page.
Why?
Because Spring Security protects application endpoints by default.
This is useful because we start with a secure baseline instead of accidentally exposing every endpoint.
But what if we want some endpoints to be public and others to require authentication?
We need to customize the security configuration.
Before that, let's understand how Spring Security actually works.
Understand the servlet filter chain
This is probably the most important section of this post.
To understand Spring Security, we first need to understand something called a Servlet Filter.
What is a servlet filter?
A Servlet Filter is a Java component that can intercept HTTP requests and responses before they reach a Servlet.
Think about a security guard standing at the entrance of an office.
Before someone enters the office, the guard can:
- Check their identity.
- Verify their entry permission.
- Reject unauthorized visitors.
- Allow authorized visitors to proceed.
A Servlet Filter works similarly.
It can inspect an incoming HTTP request before allowing it to continue through the application.
A filter implements the jakarta.servlet.Filter interface.
For example:
import jakarta.servlet.Filter; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import java.io.IOException; public class MyFilter implements Filter { @Override public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException { System.out.println("Before request processing"); chain.doFilter(request, response); System.out.println("After request processing"); } } Output for a request that continues successfully:
Before request processing After request processing Let's understand the important part:
chain.doFilter(request, response); This statement passes the request to the next filter in the chain.
Eventually, the request reaches the target Servlet.
If there are multiple filters, each one can perform some operation before and after calling chain.doFilter().
What if we don't call chain.doFilter()?
Then the request does not continue to the next filter or target Servlet through that chain.
For example:
public class MyFilter implements Filter { @Override public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException { System.out.println("Request blocked"); response.getWriter().write("Access denied"); } } Output:
Request blocked The request is stopped at the filter.
The controller never receives it.
This is exactly the kind of behaviour Spring Security uses to protect our application.
Why filters run before DispatcherServlet
Now let's connect this to Spring MVC.
You probably know the normal Spring MVC request flow:
CLIENT | v HTTP REQUEST | v DispatcherServlet | v HandlerMapping | v Controller | v Response | v CLIENT The DispatcherServlet is the front controller of Spring MVC.
It receives incoming requests and decides which controller should handle them.
But here's the important question:
Should we allow every request to reach DispatcherServlet before checking whether the user is authorized?
No.
Imagine someone tries to access:
GET /api/admin/users We should verify their permissions before allowing the request to reach the controller.
This is why Servlet Filters are useful.
Servlet filters execute before the target Servlet.
In a Spring MVC application, that target Servlet is normally DispatcherServlet.
The actual request flow looks like this:
CLIENT | v HTTP REQUEST | v +--------------------+ | SERVLET FILTERS | | | | Filter 1 | | Filter 2 | | Filter 3 | +--------------------+ | v DispatcherServlet | v Controller | v Response | v CLIENT Now you can understand why Spring Security uses filters.
It can verify requests before Spring MVC starts controller processing.
Behind the scenes
The Servlet container, such as Tomcat, manages the Servlet filter chain.
When a request arrives, the container executes registered filters according to their configured order.
Spring Security integrates into this mechanism using a special filter called DelegatingFilterProxy.
We'll understand its responsibility next.
Where FilterChainProxy and SecurityFilterChain fit
There are three important names here:
DelegatingFilterProxyFilterChainProxySecurityFilterChain
Let's understand them one by one.
1. DelegatingFilterProxy
Spring Security is managed by the Spring ApplicationContext, but Servlet filters are registered with the Servlet container.
How do these two worlds communicate?
This is where DelegatingFilterProxy comes in.
It is a Servlet Filter that delegates request processing to a Spring-managed Filter bean.
Spring Security uses it to connect the Servlet container with its security infrastructure.
2. FilterChainProxy
FilterChainProxy is a central filter provided by Spring Security.
It receives requests through the delegation mechanism and selects the appropriate security filter chain.
It also provides important infrastructure such as security context cleanup and HTTP firewall integration.
3. SecurityFilterChain
A SecurityFilterChain represents a collection of security filters that should be applied to matching requests.
For example:
- One chain can protect REST APIs.
- Another chain can protect an admin section.
- Another chain can handle browser-based form login.
This allows us to create different security configurations for different parts of our application.
Let's understand their relationship.
CLIENT | v HTTP REQUEST | v SERVLET CONTAINER | v DelegatingFilterProxy | v FilterChainProxy | v Select Matching Chain | +---------+---------+ | | v v SecurityFilterChain 1 SecurityFilterChain 2 | | v v API Security Browser Security | | +---------+---------+ | v DispatcherServlet | v Controller An important detail:
When multiple SecurityFilterChain beans exist, FilterChainProxy uses their request matchers and ordering to select the first matching chain.
It does not execute every matching security chain one after another.
Also, SecurityFilterChain itself is not the same thing as FilterChainProxy.
Think of it this way:
-
FilterChainProxyis the central coordinator. -
SecurityFilterChaindescribes which security filters should run for a particular request.
Does every request reach the controller?
No.
This is an important thing to remember.
Consider this request:
GET /api/admin/users Suppose the user is not authenticated.
Spring Security can reject the request before it reaches DispatcherServlet.
Similarly, even if the user is authenticated, they might not have permission to access the endpoint.
The request can still be rejected.
Typical HTTP responses include:
-
401 Unauthorized: Authentication is required or has failed. -
403 Forbidden: The request is understood, but access is denied.
The exact response depends on the configured authentication entry point and access-denied handling.
Behind the scenes
HTTP REQUEST | v Spring Security Filters | v Authentication Check | v Authorization Check | +-----+-----+ | | Allowed Rejected | | v v DispatcherServlet HTTP Error | v Controller Now we understand why security filters execute before the front controller.
Let's configure them.
Configure Spring Security using Java configuration
Spring Security supports Java-based configuration.
Instead of writing XML configuration, we can create a normal Java configuration class.
This is where @Configuration, @EnableWebSecurity, and SecurityFilterChain come in.
What @Configuration does
@Configuration is a Spring annotation used to declare a configuration class.
A configuration class is a place where we define and configure Spring beans.
For example:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class AppConfig { @Bean public String applicationName() { return "Library Application"; } } What happens here?
The class is marked as a configuration class.
The method annotated with @Bean tells Spring to register the returned object in the ApplicationContext.
So we have a Spring-managed bean named applicationName.
Why do we need this?
Sometimes we want to configure objects that are not discovered through component scanning.
For example:
- Security configuration.
- Database configuration.
- Custom object creation.
- Third-party library configuration.
We can define such objects using @Bean methods.
What @EnableWebSecurity does
Now let's understand @EnableWebSecurity.
This annotation enables Spring Security's web security support for Servlet-based applications.
In simple words, it activates the infrastructure needed for securing HTTP requests using Spring Security.
Example:
@Configuration @EnableWebSecurity public class SecurityConfig { } Why do we use both annotations?
@Configuration tells Spring that this is a configuration class.
@EnableWebSecurity enables the Servlet web security integration.
In a Spring Boot application using the Security starter, much of this infrastructure is already auto-configured.
Therefore, explicitly adding @EnableWebSecurity is common in examples and configuration classes, but it is not always necessary in a Spring Boot application.
Define a SecurityFilterChain bean
Now comes the most important part.
How do we tell Spring Security which endpoints are public and which endpoints require authentication?
We configure a SecurityFilterChain bean.
Let's create a simple configuration for our Library application.
package com.example.library.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain( HttpSecurity http ) throws Exception { http .authorizeHttpRequests(request -> request .requestMatchers("/public/**") .permitAll() .anyRequest() .authenticated() ) .formLogin(Customizer.withDefaults()); return http.build(); } } Let's understand what we have written.
1. HttpSecurity
public SecurityFilterChain securityFilterChain( HttpSecurity http ) HttpSecurity is an object used to configure web security.
We use it to configure:
- Which requests are allowed.
- Which requests require authentication.
- Form login.
- HTTP Basic authentication.
- CSRF protection.
- Session management.
- Custom security filters.
2. authorizeHttpRequests()
.authorizeHttpRequests(request -> request // Authorization rules ) This allows us to define authorization rules for HTTP requests.
3. requestMatchers()
.requestMatchers("/public/**") .permitAll() This tells Spring Security that all endpoints matching /public/** can be accessed without authentication.
For example:
/public/hello /public/about /public/contact All these endpoints are public.
4. anyRequest()
.anyRequest() .authenticated() This means every other request requires an authenticated user.
5. formLogin()
.formLogin(Customizer.withDefaults()); Enables the default form-based login support.
Spring Security can provide a default login page.
6. http.build()
return http.build(); This builds the configured security filter chain.
Spring registers the returned SecurityFilterChain bean and uses it to secure matching requests.
Behind the scenes
SecurityConfig | v HttpSecurity | v Configure Security Rules | v http.build() | v SecurityFilterChain | v FilterChainProxy | v Incoming HTTP Request This is how we customize Spring Security using Java configuration.
Understand request matchers and rule order
Let's understand the rules in more detail.
Consider:
.authorizeHttpRequests(request -> request .requestMatchers("/users/register", "/users/login") .permitAll() .requestMatchers("/admin/**") .hasRole("ADMIN") .anyRequest() .authenticated() ) What does this mean?
1. Registration and login
.requestMatchers("/users/register", "/users/login") .permitAll() Anyone can access these endpoints.
This makes sense because users must be able to register and log in before they are authenticated.
2. Admin endpoints
.requestMatchers("/admin/**") .hasRole("ADMIN") Only users having the ADMIN role can access these endpoints.
3. Remaining endpoints
.anyRequest() .authenticated() All remaining requests require authentication.
One important rule:
The order of authorization rules matters.
Spring Security evaluates the configured matchers in order and applies the first matching rule.
For example, this is wrong:
.authorizeHttpRequests(request -> request .anyRequest() .authenticated() .requestMatchers("/users/login") .permitAll() ) The broad anyRequest() rule must come last.
Otherwise, the later rule cannot be used as intended, and the configuration may fail to build.
What happens to the default security configuration
You might wonder:
When we define our own SecurityFilterChain bean, does Spring Boot still use its default web security configuration?
In Spring Boot, defining your own SecurityFilterChain causes the default web security configuration to back off.
That means your custom security rules become responsible for protecting the matching requests.
This is important.
Don't assume that Spring Boot will automatically combine every default authorization rule with your custom rules.
You should explicitly define the rules your application needs.
Also, defining a SecurityFilterChain does not automatically provide a user database or custom authentication provider.
Authentication configuration is another part of Spring Security.
We'll explore that in Part 2.
Cross site request forgery CSRF
Now let's understand one of the most important security concepts in Spring applications.
CSRF stands for Cross-Site Request Forgery.
You might have seen this line in Spring Security configurations:
.csrf(customizer -> customizer.disable()) Many tutorials include it when creating JWT authentication.
But why?
What is CSRF?
And should we always disable it?
Let's understand the problem first.
What is a CSRF attack?
Imagine Asha logs into her banking website:
https://bank.example.com After successful login, the server creates a session and sends a session cookie to her browser.
For example:
Set-Cookie: JSESSIONID=abc123 The browser stores this cookie.
Whenever Asha sends another request to the same website, the browser automatically includes the cookie.
Now imagine Asha opens another website created by an attacker:
https://attacker.example.com The attacker has created a malicious form that sends a request to Asha's banking website.
For example:
<form action="https://bank.example.com/transfer" method="POST"> <input name="amount" value="5000"> <input name="to" value="attacker"> <button type="submit"> Click here </button> </form> Asha clicks the button.
What happens?
Her browser sends the request to the banking website.
Because the browser already has the banking session cookie, it may automatically attach that cookie to the request.
The banking server receives:
POST /transfer Cookie: JSESSIONID=abc123 amount=5000 to=attacker The server sees a valid authenticated session.
It might think Asha intentionally initiated this transaction.
But she didn't.
The request was triggered by another website.
This is called a CSRF attack.
Behind the scenes
ASHA LOGS INTO BANK | v Bank Sends Cookie | v Browser Stores Cookie | v Asha Opens Attacker Website | v Attacker Triggers POST | v Browser Sends Request | v Bank Cookie Is Attached | v Bank Receives Request | v CSRF ATTACK The important thing to understand:
The attacker doesn't necessarily need to know Asha's password or session cookie.
The browser automatically attaches the existing cookie.
That's the vulnerability CSRF protection is designed to address.
How Spring Security protects against CSRF
Spring Security enables CSRF protection by default for Servlet-based applications.
It uses a CSRF token to verify that a state-changing request was intentionally initiated by a trusted application context.
A CSRF token is a unique, unpredictable value associated with the user's request/session context.
For example:
CSRF Token: x7y8z9abc123 When the application renders a form, it includes the token as a hidden field.
Example:
<form action="/transfer" method="POST"> <input type="hidden" name="_csrf" value="x7y8z9abc123"> <input name="amount" value="5000"> <button type="submit"> Transfer </button> </form> When the user submits the form, the token is sent along with the request.
Spring Security checks whether the submitted token matches the expected token.
If it matches, the request can continue through the security chain.
If it is missing or invalid, the request is rejected.
Behind the scenes
User Opens Form | v Server Generates CSRF Token | v Form Contains Token | v User Submits Form | v Request Includes Token | v Spring Security Validates | +----+----+ | | Valid Invalid | | v v Continue HTTP 403 Spring Security's default CSRF request matcher protects unsafe HTTP methods.
These include:
- POST
- PUT
- PATCH
- DELETE
Safe methods such as GET, HEAD, OPTIONS, and TRACE are not protected by the default CSRF matcher.
Why?
Because GET requests should be used for retrieving data, not changing application state.
Should you disable CSRF for a JWT API?
This is where many beginners get confused.
You might see configurations like this:
http .csrf(customizer -> customizer.disable()); Why would someone disable CSRF?
Because many REST APIs use bearer tokens.
For example:
GET /api/profile Authorization: Bearer eyJhbGciOi... Here, the client explicitly adds the token to the Authorization header.
A browser does not automatically attach an Authorization bearer token from JavaScript's local storage to every cross-site request.
Therefore, this authentication setup generally does not have the same automatic-cookie behaviour that creates the traditional CSRF problem.
For this kind of API, disabling CSRF can be appropriate.
But there is an important exception.
Using JWT does not automatically mean CSRF protection is unnecessary.
Suppose you store your JWT inside an authentication cookie:
Set-Cookie: accessToken=eyJhbGciOi... The browser automatically sends that cookie with matching requests.
Now the same CSRF concern can exist.
The token format is JWT, but the way the browser sends the credential still matters.
So remember:
JWT in Authorization Header | v Explicitly attached by client | v Usually no traditional CSRF risk JWT in Authentication Cookie | v Automatically attached by browser | v CSRF protection may be required My recommendation:
- Session-based browser authentication: Keep CSRF enabled.
- JWT passed explicitly through the Authorization header: Disabling CSRF may be appropriate after reviewing the complete authentication design.
- JWT stored in cookies: Keep appropriate CSRF protection.
Don't disable CSRF just because your application uses JWT.
CSRF is not CORS
Another common confusion is between CSRF and CORS.
They solve different problems.
CSRF:
Protects a website from unauthorized state-changing requests triggered by another site using the victim's existing authentication context.
CORS:
Cross-Origin Resource Sharing is a browser mechanism that controls whether JavaScript from one origin can access responses from another origin.
For example:
Frontend: http://localhost:3000 Backend: http://localhost:8080 These are different origins because their ports are different.
Your browser may enforce CORS rules when the frontend tries to access the backend.
But CORS is not a replacement for CSRF protection.
A server should configure both according to the application's architecture.
Connect this to your SecurityConfig
Now let's connect what we learned to the code you provided.
Your package:
com.test.SpringSecEx.Config Your main configuration:
SecurityConfig.java
You have written:
@Configuration @EnableWebSecurity public class SecurityConfig { @Autowired private JwtFilter jwtFilter; @Bean public SecurityFilterChain securityFilterChain( HttpSecurity http, JWTService jwtService ) { return http .csrf(customizer -> customizer.disable()) .authorizeHttpRequests(request -> request .requestMatchers( "/users/register", "/users/login" ) .permitAll() Source:https://dev.to/mayur_bodhare/spring-security-explained-filters-securityfilterchain-and-csrf-42knRelated posts
円形・八角形ラグの干渉判定を外接矩形ではなく頂点と円で扱う設計
How to Use an AI Wallpaper Generator for Clean Desktop and Phone Backgrounds (Without Clutter)
GLM-5.4 Generated a 3D Design. Can You Change One Dimension Without Rebuilding It?
Best color memory games for training swatch recall

69 Best Websites for Buying Aged Gmail Accounts in Bulk
