Hello! Welcome to the sixth lesson in our journey to build a production-grade blog platform.
In our last session, we built a sophisticated global exception handler. We learned to distinguish between validation failures (bad client input) and application-level failures (business logic violations), creating separate handlers for each. This allows our API to provide clear, context-aware error responses—a 400 Bad Request for a malformed request body and a 404 Not Found for a missing resource.
With robust data handling and error management in place, it's time to address a critical component of any real-world application: security. This brings us to today's lesson, where we'll tackle the following learning outcome:
Configure a Spring Security filter chain to secure endpoints, comparing its architecture to Express middleware.
Today, we will lay the foundation for our entire authentication and authorization system. We'll introduce the Spring Security framework, demystify its core architectural pattern—the SecurityFilterChain—and draw direct parallels to the middleware concepts you're already an expert in from your MERN stack experience.
The "Magic" of Spring Security: An Introduction to Servlet Filters
When you first add Spring Security to a project, it can feel like "magic." Suddenly, all your endpoints are protected, and a login page appears out of nowhere. This magic is powered by a concept fundamental to Java web applications: Servlet Filters.
Think of a filter exactly as you think of middleware in Express.js. It's a piece of code that can intercept, inspect, and even modify an incoming HTTP request and the outgoing response before it reaches your controller's business logic.
Just as you can chain multiple middleware functions in Express, Java web applications use a FilterChain.

To understand this architecture in more detail, let's start with the official Spring Security documentation.
Please read the following sections from the official Spring Security documentation. They provide the foundational theory behind its architecture.
First, read 'A Review of Filters' to grasp the basic concept. Then, read 'FilterChainProxy' and 'SecurityFilterChain' to understand how Spring Security manages its own dedicated chain of filters. Pay close attention to the diagrams and the idea that filters are ordered and can be configured for different URL patterns. Note the similarity of the doFilter method signature to Express's (req, res, next) function.
This filter-based architecture is the key to Spring Security's power and flexibility. It allows for cross-cutting concerns like authentication, authorization, CSRF protection, and header manipulation to be applied declaratively.
Configuring Your First SecurityFilterChain
Let's get hands-on. The first step is to add the Spring Security dependency to your pom.xml.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Runtime Observation #1: If you add this dependency and restart your application, you'll immediately see a change. Any request you make via Postman will now likely result in a 401 Unauthorized response, and if you open the endpoint in a browser, you'll be redirected to a default login page. Spring Boot's auto-configuration provides a "secure-by-default" setup.
Our goal is to override this default behavior with our own custom rules. We do this by defining a SecurityFilterChain bean in a configuration class.
Watch this segment from a talk by Spring Security engineer Daniel Garnier-Moiroux. He does an excellent job of explaining the modern, lambda-based approach to configuration.
Spring Security Architecture Principles by Daniel Garnier-Moiroux @ Spring I/O 2024
This video demonstrates the modern, recommended way to configure Spring Security. It addresses common points of confusion and establishes a clear pattern.
Watch from 06:02 to 08:41. Focus on how a SecurityFilterChain bean is created within a @Configuration class. Pay attention to the http.authorizeHttpRequests(...) block, where he defines which paths are public (permitAll) and which require authentication (authenticated). This is the core of what we are about to implement.
Now, let's create our own configuration.
- Create a new package
com.example.blogplatform.config. - Inside, create a class named
SecurityConfig.java.
package com.example.blogplatform.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
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 // Enables Spring Security's web security support
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
// 1. Disable CSRF for stateless REST APIs. We will use JWTs which are stateless.
.csrf(csrf -> csrf.disable())
// 2. Define authorization rules
.authorizeHttpRequests(authz -> authz
// Allow public access to GET requests for posts
.requestMatchers(HttpMethod.GET, "/api/posts/**").permitAll()
// Allow public access to user registration and login endpoints
.requestMatchers(HttpMethod.POST, "/api/auth/register", "/api/auth/login").permitAll()
// All other requests must be authenticated
.anyRequest().authenticated()
);
return http.build();
}
}
Code Breakdown:
csrf(csrf -> csrf.disable()): In traditional web apps, CSRF protection is crucial. However, for a stateless REST API that uses tokens for authentication (which we will build), CSRF attacks are less of a concern. We disable it for simplicity in our API context.authorizeHttpRequests(...): This is the heart of our configuration, the direct equivalent of setting up route-specific middleware in Express.requestMatchers(...): We use this to specify URL patterns and HTTP methods.permitAll(): Allows anonymous access.authenticated(): Requires the user to be logged in..anyRequest().authenticated(): This is a powerful "deny by default" rule. Any request that doesn't match the preceding rules will be rejected unless the user is authenticated.
MERN vs. Spring: A Direct Comparison
Let's formalize the comparison between Express Middleware and Spring Security Filters.
| Feature | Express.js Middleware | Spring Security Filter |
|---|---|---|
| Core Concept | A function: (req, res, next) => { ... } |
A class implementing Filter with doFilter(...) |
| Purpose | Intercept and process requests/responses | Intercept and process requests/responses |
| Passing Control | Call next() to invoke the next middleware. |
Call chain.doFilter(req, res) to invoke the next filter. |
| Ending the Cycle | Call res.send(), res.json(), etc., and don't call next(). |
Write to the response and return without calling chain.doFilter(). |
| Registration | app.use(myMiddleware) in server.js or equivalent. |
http.addFilterBefore(...) inside the SecurityFilterChain bean. |
| Configuration | Applied imperatively in code, order matters. | Configured declaratively via a HttpSecurity builder, order is critical. |
This article provides another perspective that explicitly frames Spring Security filters as middleware, which should resonate with your background.
Spring Security — The Security Filter Chain
This article reinforces the analogy between filters and middleware and lists the key filters involved in the security process.
Read the sections that introduce filters as 'Middleware' using the 'chain of responsibility pattern'. Then, look at the list of 'Core Components of the Spring Security Filter Chain' to see the different types of security tasks that are handled by dedicated filters.
Runtime Observation & Debugging: Peeking Under the Hood
Now that we have our custom rules, let's verify them.
- Restart your application.
- Test a public endpoint: Send a
GETrequest to/api/postsin Postman. It should return a200 OKas expected. - Test a private endpoint: Send a
POSTrequest to/api/posts. It should now fail with a401 Unauthorized(or sometimes403 Forbidden). Spring Security has blocked the request because it requires authentication, and we haven't provided any.
This is good, but what's really happening? To satisfy your "debugging-first" preference, here is the single most valuable trick for debugging Spring Security: enable TRACE logging.
In your application.properties (or application.yml), add the following line:
logging.level.org.springframework.security=TRACE
Now, restart the application and re-run the POST request to /api/posts. Look at your console logs. You will see a verbose output detailing every single filter in the SecurityFilterChain being invoked for your request.
... TRACE ... o.s.security.web.FilterChainProxy : Securing POST /api/posts
... TRACE ... o.s.security.web.FilterChainProxy : Invoking CsrfFilter (4/15)
... TRACE ... o.s.security.web.FilterChainProxy : Invoking LogoutFilter (5/15)
...
... TRACE ... o.s.security.web.FilterChainProxy : Invoking AuthorizationFilter (15/15)
... DEBUG ... o.s.s.w.a.ExceptionTranslationFilter : Sending 401 Unauthorized error...
This log output is your best friend. It shows you:
- Which filters are running.
- The order they run in.
- Which filter ultimately made the decision to deny the request (in this case,
AuthorizationFilterwill find no authentication andExceptionTranslationFilterwill handle the resulting error).
This technique is highlighted in both the official documentation and the Spring I/O talk as the primary way to debug complex security scenarios.
Implementing a Custom Filter (The Hands-On Part)
To solidify your understanding, let's create a simple custom filter that logs the remote address of every incoming request.
- In your
configpackage, create a new classRequestLoggingFilter.java.
package com.example.blogplatform.config;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
// Extend OncePerRequestFilter to guarantee the filter is executed only once per request.
public class RequestLoggingFilter extends OncePerRequestFilter {
private static final Logger logger = LoggerFactory.getLogger(RequestLoggingFilter.class);
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
// Logic before the request goes to the controller
logger.info("Incoming request: {} {} from {}", request.getMethod(), request.getRequestURI(), request.getRemoteAddr());
// This is the equivalent of calling next() in Express.
filterChain.doFilter(request, response);
// Logic after the request has been processed
// We could log the response status here, for example.
}
}
- Now, we must register this filter in our
SecurityConfig. We'll add it at a specific point in the chain. A common place to add logging or initial processing filters is before the main authentication filters.
// In SecurityConfig.java
// Import the filter you just created
import com.example.blogplatform.config.RequestLoggingFilter;
// Import the filter we will place our new filter before
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
// ... inside the securityFilterChain method, before `return http.build()`
http.addFilterBefore(new RequestLoggingFilter(), BasicAuthenticationFilter.class);
return http.build();
The addFilterBefore method explicitly places our custom filter in the chain before the BasicAuthenticationFilter, which is one of Spring's default authentication mechanisms.
Runtime Observation #3: Restart the application and make any request. You will now see your custom log message printed to the console for every single request, confirming your filter is active in the chain.
Conclusion
Congratulations! You've successfully configured your first SecurityFilterChain and gained a deep, practical understanding of Spring Security's core architecture. You've demystified the "magic" and can now see it for what it is: a powerful, ordered chain of filters, directly analogous to the middleware pattern you've mastered in the MERN world.
Key Takeaways:
- Spring Security is built upon Servlet Filters and the
FilterChain, which functions like an Express.js middleware chain. - We configure security rules by creating a
@Beanof typeSecurityFilterChainin a@Configurationclass. - The
HttpSecurityobject provides a declarative DSL to define rules, such as disabling CSRF and usingauthorizeHttpRequeststo secure specific endpoints. - The rule
.anyRequest().authenticated()establishes a secure-by-default posture. - Enabling
TRACElogging fororg.springframework.securityis the most effective way to debug the filter chain and understand its behavior at runtime. - Custom filters can be created by extending
OncePerRequestFilterand added to the chain with methods likeaddFilterBefore.
Preview of the Next Lesson:
Our API now correctly distinguishes between public and private endpoints. However, there's no way for a user to prove who they are. In our next lesson, "Implement a user registration endpoint that hashes passwords using BCrypt and persists user details," we will build the first piece of our authentication puzzle. We'll create the User entity, set up the registration logic, and ensure we store user passwords securely using a standard hashing algorithm.