JWT Authentication Flow in Spring Boot REST API
Fast recall
Quick revision
Core answer
JwtDecoder, validates claims such as issuer and expiry, converts accepted claims to authorities, and places the resulting Authentication in the SecurityContext. Request or method authorization then decides access. A custom OncePerRequestFilter is possible, but it is not the normal starting point.Interview-ready guide
Interview answer
JWT authentication in a Spring Boot API has an issuance step and a request-validation step. An authorization service first verifies the login and issues a signed access token. The client then sends that token as Authorization: Bearer ... when it calls the API.
Spring Security's OAuth2 Resource Server support extracts the bearer token and gives it to a JwtDecoder. The decoder verifies the signature with a trusted key and validates claims such as issuer, expiry, and not-before. The service should also validate audience when the token is meant for a particular API. Spring converts accepted scopes or roles into authorities and creates an Authentication in the SecurityContext for that request.
Request or method authorization then checks whether those authorities allow the action. A missing or invalid token commonly produces 401, while a valid token without permission commonly produces 403. A stateless policy means the context is rebuilt from the token on each request rather than stored in an HTTP session. Spring already provides this flow; a hand-written OncePerRequestFilter is only needed for a genuinely non-standard token scheme.
JWT Authentication Flow in Spring Boot REST API
Direct Answer
In a Spring Boot API, an authorization service first authenticates the user and issues a signed access token. On later requests, Spring Security's OAuth2 Resource Server support reads the bearer token, verifies it with a configured JwtDecoder, validates claims such as issuer and expiry, converts accepted claims to authorities, and places the resulting Authentication in the SecurityContext. Request or method authorization then decides access. A custom OncePerRequestFilter is possible, but it is not the normal starting point.
Code Example
@Bean
SecurityFilterChain apiSecurity(HttpSecurity http) throws Exception {
http
.securityMatcher("/api/**")
.sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.csrf(csrf -> csrf.disable())
.oauth2ResourceServer(resourceServer -> resourceServer.jwt(Customizer.withDefaults()))
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/admin/**").hasAuthority("SCOPE_admin")
.anyRequest().authenticated());
return http.build();
}
spring.security.oauth2.resourceserver.jwt.issuer-uri=https://auth.example
With issuer discovery configured, Spring obtains trusted signing keys and validates the token issuer and time claims. Add an audience validator when the issuer serves tokens for more than one resource.
Common Mistakes & Pitfalls
- Forgetting to set sessionCreationPolicy to STATELESS: Freshers often leave the default session policy, so Spring creates HTTP sessions even though you're using JWT. This defeats the purpose and wastes memory. Always configure SecurityConfig with sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).
- Not checking if Authentication is already set: The filter runs on every request, and if you don't check SecurityContextHolder.getContext().getAuthentication() == null, you might reprocess the same token multiple times or override existing authentication. The null check prevents redundant work.
- Validating the token after setting SecurityContext: Some implementations extract the username, set authentication, then validate — by that point the request is already authenticated with potentially invalid data. Always validate the token signature BEFORE setting the Authentication object.
Check your understanding
Answer these without looking back at the article.
- How do you handle JWT token expiry — what response does the client receive?
- What is the purpose of OncePerRequestFilter?
- How would you implement token refresh in a JWT-based system?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.