Welcome to the final lesson in our module on Spring Boot. In our previous session, we walked through the OAuth2 Authorization Code grant flow, which concluded with a client application successfully obtaining an access token. In many modern systems, especially in microservice architectures, this access token is a JSON Web Token (JWT).
Now, we'll explore the other side of the transaction. Once the client has the JWT, it will use it to make authenticated requests to your backend services. This lesson will demystify what happens inside a Spring Boot application when it receives such a request. You will learn to explain how Spring Security's filter chain validates JWTs on incoming requests.
Understanding this process is critical for backend interview deep-dives, as it demonstrates a firm grasp of Spring Security's core architecture and its application in securing stateless services—a cornerstone of the microservices you design and build.
1. The Foundation: Spring Security's Filter Chain
Before we can understand how a JWT is validated, we must first understand how Spring Security intercepts an HTTP request at all. The entire framework is built upon the concept of a servlet Filter chain.
A Filter is an object that can intercept and process an HTTP request before it reaches the intended endpoint (like a @RestController method) and can also process the response on its way out. Spring Security installs a chain of these filters, each with a specific security responsibility, such as handling CSRF protection, session management, or authentication.
The following video from a Spring I/O conference, presented by Spring engineer Daniel Garnier-Moiroux, provides an excellent and authoritative explanation of this core principle.
Spring Security Architecture Principles by Daniel Garnier-Moiroux @ Spring I/O 2024
This video explains the fundamental role of filters and the security filter chain in Spring Security's architecture.
Watch the section from this segment to understand how filters intercept requests, form a chain, and pass control to one another. Pay close attention to the doFilter method and the visual representation of the call stack.
When a request arrives, it passes through this chain. For a request containing a JWT, one specific filter in this chain is responsible for spotting it, extracting it, and initiating the validation process.
2. Anatomy of a JWT-Authenticated Request
When a client makes an authenticated API call, it includes the JWT in the Authorization HTTP header, using the "Bearer" scheme.
Authorization: Bearer <your-jwt-here>
As a brief refresher, a JWT consists of three parts separated by dots: header.payload.signature.

The stateless nature of JWTs is a significant advantage in microservices. The resource server can validate the token's authenticity and the claims within it—such as the user's identity (sub), their permissions (scope), and the token's expiration time (exp)—without needing to contact the original authorization server. This self-contained verification is highly efficient.
3. The Modern Approach: OAuth2 Resource Server
Spring Boot provides a robust, production-grade mechanism for handling JWTs through the spring-boot-starter-oauth2-resource-server dependency. When you configure your application as a resource server, Spring Security automatically wires in the necessary components for JWT validation.
The official Spring Security documentation provides the most accurate depiction of this process. Let's break down the key components involved.
OAuth 2.0 Resource Server JWT :: Spring Security
This section of the Spring Security documentation details the internal components and the flow of JWT validation.
Please read the section titled "How JWT Authentication Works". As you read, focus on understanding the roles of these five components: BearerTokenAuthenticationFilter: This is the filter in the chain that scans the request for an Authorization: Bearer ... header. It extracts the raw token string and wraps it in a BearerTokenAuthenticationToken, which is an unauthenticated request object. AuthenticationManager: The filter passes this token to the AuthenticationManager. Its job is to orchestrate the authentication by finding an AuthenticationProvider that can handle this specific type of token. JwtAuthenticationProvider: This is the specialized provider that understands JWTs. It delegates the complex work of parsing and validation to a JwtDecoder. JwtDecoder: This component is responsible for the actual validation logic. It performs several critical checks: It verifies the token's cryptographic signature against the public keys of the authorization server. It validates standard claims, such as the expiration time (exp) and issuer (iss). JwtAuthenticationConverter: Once the JwtDecoder confirms the token is valid, this converter's job is to transform the validated Jwt object into a fully authenticated Authentication object (specifically, a JwtAuthenticationToken). It typically extracts claims like scope or scp and maps them to GrantedAuthority objects, which are then used for authorization decisions.
After this process, the resulting authenticated Authentication object is placed into the SecurityContextHolder. This context holds the security identity for the duration of the request, making it available for authorization checks downstream.

Configuration in Practice
A key strength of Spring Boot is its auto-configuration. To enable all the machinery we just discussed, you often only need to provide the issuer's URI in your application.yml:
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: https://your-auth-server.com/auth/realms/your-realm
With this single property, Spring Security will:
- Discover the authorization server's metadata endpoint (often a
.well-known/openid-configurationURL). - Find the
jwks_urifrom that metadata, which points to the public keys used for signature validation. - Configure the
JwtDecoderto use these keys and validate theissclaim against the providedissuer-uri.
4. The Custom Filter Approach
While the oauth2-resource-server starter is the recommended approach, in many codebases and online tutorials, you'll find a manual implementation involving a custom filter. It's essential to recognize this pattern for interviews.
This approach typically involves:
- A
JwtServiceclass: A helper class you write that uses a library likejjwtto handle token parsing, signature verification, and claim extraction. - A custom
JwtFilter: A filter you create, usually by extendingOncePerRequestFilter, that is manually added to the security filter chain.
The logic inside this custom filter's doFilterInternal method usually follows these steps:
- Extract the
Authorizationheader from theHttpServletRequest. - Parse the "Bearer " token string.
- Use the
JwtServiceto validate the token's signature and expiration. - If the token is valid, retrieve the user's details (often from the token itself, or sometimes by querying the database using the username from the token).
- Manually create an
Authenticationobject (e.g.,UsernamePasswordAuthenticationToken). - Set this object in the
SecurityContextHolderusingSecurityContextHolder.getContext().setAuthentication(...). - Finally, call
filterChain.doFilter(request, response)to pass the request along.
The article "Integrating JWT with Spring Security 6" provides a clear, practical example of this custom filter implementation.
Integrating JWT with Spring Security 6 in Spring Boot 3
This resource shows a full implementation of a custom JWT filter.
Focus on the code and explanation for the JwtFilter.java class within this section. Compare the logic described (extracting the header, validating the token, setting the security context) with the implementation in the code snippet.
Trade-offs: The custom filter approach offers maximum flexibility but comes with the cost of writing and maintaining significant boilerplate code. You become responsible for security-critical logic like key management. The official oauth2-resource-server is more robust, declarative, and handles complexities like automatic JWK set key rotation for you. Being able to articulate these trade-offs is a hallmark of a senior engineer.
5. A Critical Interview Point: JWT Revocation
A common follow-up question in interviews is: "Since JWTs are stateless, how do you immediately log a user out or revoke their access before the token expires?"
This is a classic problem. Because the resource server validates the token without consulting the authorization server, it has no knowledge of events like a user-initiated logout or an admin banning the user.
Json Web Token (JWT) Explained from Scratch | Spring Security 6
This video discusses the challenge of token revocation with stateless JWTs and proposes some solutions.
Watch the final segment from this point, where the presenter highlights the disadvantage of a purely stateless design and touches on potential workarounds.
Here are the common strategies to address this, each with its own trade-offs:
- Keep token lifetimes short: Tokens that expire quickly (e.g., 5-15 minutes) limit the window of exposure. This is often paired with long-lived refresh tokens.
- Maintain a revocation list: This involves creating a blacklist of revoked token IDs (
jticlaim). When validating a JWT, your filter must also check if its ID is on this list (often stored in a fast cache like Redis). This re-introduces a degree of statefulness, trading pure statelessness for stronger security. - Rely on refresh token revocation: In this model, only the long-lived refresh token can be revoked. Once the short-lived access token expires, the user cannot get a new one.
Conclusion
This lesson concludes our module on Spring Boot, connecting the dots from OAuth2 theory to the practical, in-the-weeds implementation of JWT validation within Spring Security.
Your key takeaways for any technical interview should be:
- Spring Security is fundamentally a chain of servlet filters.
- The modern way to validate JWTs is with the
oauth2-resource-serverstarter, which automatically configures theBearerTokenAuthenticationFilter,JwtAuthenticationProvider, andJwtDecoder. - The validation process involves verifying the token's signature and its claims (like
exp,iss, andaud). - A valid JWT is converted into an
Authenticationobject and stored in theSecurityContextHolderfor the duration of the request. - You should be able to recognize the custom filter pattern and discuss its trade-offs against the declarative starter-based approach.
- Be prepared to discuss advanced topics like stateless token revocation strategies.
With this, you have a solid foundation in Spring Boot's core concepts, from dependency injection to security internals. In our next module, we will shift our focus to another critical component of modern microservice architectures: High-Performance Caching with Redis. We'll begin by comparing Redis's persistence mechanisms, RDB snapshots and the Append-Only File (AOF).