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?
- Understand the servlet filter chain
- Configure Spring Security using Java configuration
- Cross site request forgery CSRF
- Connect this to your SecurityConfig
- 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()
.anyRequest()
.authenticated()
)
.formLogin(Customizer.withDefaults())
.httpBasic(Customizer.withDefaults())
.sessionManagement(session ->
session.sessionCreationPolicy(
SessionCreationPolicy.STATELESS
)
)
.addFilterBefore(
jwtFilter,
UsernamePasswordAuthenticationFilter.class
)
.build();
}
}
I've removed the other authentication provider and in-memory user configuration here so we can focus on the filter chain.
What your current configuration is doing
Let's understand each part.
1. Configuration class
@Configuration
@EnableWebSecurity
public class SecurityConfig {
}
You are declaring a Spring configuration class and enabling web security.
2. JWT filter injection
@Autowired
private JwtFilter jwtFilter;
You are injecting your custom JWT filter.
We will understand how this filter works in Part 3.
3. Disable CSRF
.csrf(customizer -> customizer.disable())
This disables Spring Security's CSRF protection.
Whether this is appropriate depends on how your JWT is sent and stored.
For a stateless API that accepts bearer tokens only through the Authorization header, it can be appropriate.
4. Public endpoints
.requestMatchers(
"/users/register",
"/users/login"
)
.permitAll()
Users can register and log in without already being authenticated.
This is necessary because these endpoints are responsible for starting the authentication process.
5. Protect every other endpoint
.anyRequest().authenticated()
All other requests require authentication.
6. Form login
.formLogin(Customizer.withDefaults())
Enables Spring Security's form-based login.
7. HTTP Basic
.httpBasic(Customizer.withDefaults())
Enables HTTP Basic authentication.
This authentication mechanism sends username and password credentials using the HTTP Authorization header.
8. Stateless session management
.sessionManagement(session ->
session.sessionCreationPolicy(
SessionCreationPolicy.STATELESS
)
)
This tells Spring Security not to create an HTTP session or use one to obtain the SecurityContext for authentication.
We'll compare stateful and stateless authentication in Part 3.
9. Add your JWT filter
.addFilterBefore(
jwtFilter,
UsernamePasswordAuthenticationFilter.class
)
This registers your custom JWT filter before Spring Security's UsernamePasswordAuthenticationFilter.
The purpose is to inspect the incoming bearer token before the later username/password authentication filter position in the chain.
We'll go through the complete JWT filter in Part 3.
Why the complete configuration needs careful choices
Your code is a useful learning example, but there is one architectural point worth discussing.
You currently combine:
.formLogin(Customizer.withDefaults())
.httpBasic(Customizer.withDefaults())
.sessionManagement(session ->
session.sessionCreationPolicy(
SessionCreationPolicy.STATELESS
)
)
.addFilterBefore(
jwtFilter,
UsernamePasswordAuthenticationFilter.class
)
These are different authentication mechanisms.
- Form login: Browser-based username and password authentication.
- HTTP Basic: Username and password sent using an HTTP Authorization header.
- JWT: Bearer-token-based authentication.
- Stateless session policy: Avoids using an HTTP session to persist the security context.
They can coexist in some carefully designed applications, but enabling all of them does not automatically make the application more secure.
For a JWT-only REST API, you would generally configure JWT authentication and avoid enabling form login or HTTP Basic unless you have a specific requirement for them.
For a session-based browser application, you would generally use form login and retain CSRF protection.
We'll refactor your complete configuration after understanding the authentication process and JWT lifecycle.
Which one should I use?
Let's summarize the important concepts.
Servlet Filter
Use a Servlet Filter when you need to intercept requests or responses at the Servlet container level.
DispatcherServlet
Use it as the entry point for Spring MVC request handling. Security filters normally execute before it.
FilterChainProxy
Spring Security's central filter that delegates requests to the matching security filter chain.
SecurityFilterChain
Use it to define which security filters and HTTP security rules should apply to a group of requests.
@Configuration
Use it to declare Spring configuration classes and bean definitions.
@EnableWebSecurity
Use it to explicitly enable Servlet-based Spring Security configuration when appropriate.
CSRF protection
Keep it enabled for session and cookie-based browser authentication.
Disable it only when the application's authentication design makes CSRF protection unnecessary.
What should be my default approach?
For most Spring Boot applications, start with one clearly defined SecurityFilterChain.
Explicitly define:
- Public endpoints.
- Protected endpoints.
- Authentication mechanisms.
- CSRF policy.
- Session policy.
Add multiple security chains only when different parts of the application genuinely need different security behaviour.
Common mistakes
1. Thinking DispatcherServlet is the first component to receive every request
Servlet filters execute before the target Servlet.
Understand the Servlet lifecycle before debugging security issues.
2. Confusing FilterChainProxy with SecurityFilterChain
FilterChainProxy selects and executes a matching SecurityFilterChain.
One is the coordinator, while the other represents the configured security filters for matching requests.
3. Putting anyRequest() before specific matchers
Authorization rules are evaluated in order.
Always place broad catch-all rules such as anyRequest() after your specific matchers.
4. Assuming @EnableWebSecurity creates your complete authentication system
It enables web security infrastructure.
You still need to configure authentication, authorization, and the appropriate security filters.
5. Disabling CSRF whenever you use JWT
JWT format alone does not determine CSRF risk.
Consider whether credentials are automatically attached by the browser, particularly when using cookies.
6. Enabling every authentication mechanism without understanding the architecture
Form login, HTTP Basic, sessions, and JWT serve different use cases.
Choose the mechanisms your application actually needs.
Quick recap
- Spring Security provides authentication, authorization, and protection against common attacks.
- Authentication verifies who the user is.
- Authorization determines what the user can access.
- Servlet Filters intercept requests before they reach the target Servlet.
- DispatcherServlet is Spring MVC's front controller.
- Spring Security uses DelegatingFilterProxy to integrate with the Servlet container.
- FilterChainProxy selects the appropriate SecurityFilterChain.
- SecurityFilterChain contains the security filters for matching requests.
-
@Configurationdeclares configuration classes. -
@Beanregisters objects in the Spring container. -
@EnableWebSecurityenables Servlet-based web security infrastructure. -
HttpSecurityconfigures HTTP security behaviour. -
authorizeHttpRequests()defines request authorization rules. -
requestMatchers()identifies request patterns. -
permitAll()allows public access. -
authenticated()requires an authenticated user. -
hasRole()restricts access based on roles. - CSRF stands for Cross-Site Request Forgery.
- Spring Security enables CSRF protection by default.
- Cookie-based authentication needs careful CSRF protection.
- JWT authentication through an explicit Authorization header has different CSRF characteristics from JWT authentication stored in cookies.
- CORS and CSRF solve different security problems.
Try it yourself
Practice idea:
Create a simple Spring Boot application with these endpoints:
GET /public/hello
GET /api/profile
GET /admin/dashboard
Configure Spring Security so that:
-
/public/**is accessible without authentication. -
/api/**requires authentication. -
/admin/**requires the ADMIN role.
Use a custom SecurityFilterChain bean.
Run the application and observe what happens when you access each endpoint.
Bonus experiment:
Create a custom Servlet Filter that logs:
Before request processing
After request processing
Register it and observe where it executes relative to DispatcherServlet.
Then add Spring Security and understand how its filters are integrated into the request lifecycle.
Try sending a POST request without a CSRF token and observe the response.
If this helped, or if you spotted something I should fix, tell me in the comments. I'm still learning too.
Top comments (0)