Spring Security for REST APIs: a stateless filter chain, login and JWT with the resource server
Hands-on Spring Boot 4 / Spring Security 7: a filter chain for a stateless API, password storage with DelegatingPasswordEncoder, a login endpoint with AuthenticationManager, issuing JWTs with NimbusJwtEncoder, validating them with the resource server, mapping a roles claim to ROLE_, JSON 401/403 and CORS for an SPA.
On this page
JWT, sessions and token pitfalls are covered in authentication: session cookies and JWT; this post is the hands-on part on Spring Boot 4 and Spring Security 7. By the end you can configure a stateless API yourself: login returns an access token, every later request carries Authorization: Bearer, and 401/403 come back as proper JSON. All code comes from a lab whose tests were run (JDK 21, Boot 4.0.3).
1. The problem
An AI writes a OncePerRequestFilter that parses JWTs itself and "trusts" the alg header. A token edited to alg: none calls GET /api/v1/users and leaks the whole employee list. Tests only cover valid tokens, so they stay green.
2. Key idea
The filter chain is the security desk at the building's door; the controller is an office inside. Someone stopped at the door never meets the receptionist inside, so @RestControllerAdvice never sees a 401/403.
| Filter | Job |
|---|---|
BearerTokenAuthenticationFilter |
reads the token from the header, calls JwtDecoder, puts the Authentication into the SecurityContext |
ExceptionTranslationFilter |
unauthenticated → 401, missing permission → 403 |
AuthorizationFilter |
checks authorizeHttpRequests rules (replaces the old FilterSecurityInterceptor) |
2.1 Who issues tokens?
| Choice | Use when | Don't use when |
|---|---|---|
| Your own HS256 JWTs + resource server | one API, your own frontend | many services: whoever holds the secret can sign tokens |
| External IdP (Keycloak, Auth0) + RS256/JWKS | many services, SSO, MFA | a small app with nobody to run an IdP |
| Spring Authorization Server | you are an OAuth2 provider for third parties | you only need login for your own app |
2.2 What must the decoder check?
| Check | Prevents |
|---|---|
| Pinned algorithm | switching alg to none or RS256 → HS256 |
iss (and aud with several APIs) |
tokens from another system |
| Key ≥ 256 bits | a "123456" secret brute-forced offline from one token |
- A JWT is signed, not encrypted: anyone can read the payload. Keep PII out of claims.
- Turning CSRF off is safe only while the access token is in a header. Move it to a cookie and CSRF comes back.
- Login:
AuthenticationManager+DaoAuthenticationProviderchecks the password (DelegatingPasswordEncoder; BCrypt reads only the first 72 bytes), then signs a 15-minute access token. - Keep the access token in JS memory, not
localStorage; the refresh token goes in anHttpOnlycookie.
3. In Java
@Bean
SecurityFilterChain api(HttpSecurity http, ProblemJsonSecurityHandlers problems) throws Exception {
http.securityMatcher("/api/**")
.csrf(csrf -> csrf.disable()) // token in a header, not a cookie
.cors(Customizer.withDefaults()) // preflight OPTIONS passes first
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(a -> a
.requestMatchers("/api/v1/auth/**").permitAll()
.requestMatchers("/api/v1/users/**").hasRole("HR")
.anyRequest().denyAll()) // forgot a rule -> 403
.oauth2ResourceServer(o -> o
.jwt(j -> j.jwtAuthenticationConverter(rolesConverter())) // "roles":["HR"] -> ROLE_HR
.authenticationEntryPoint(problems).accessDeniedHandler(problems))
.exceptionHandling(e -> e.authenticationEntryPoint(problems).accessDeniedHandler(problems));
return http.build();
}
// no token -> 401 + WWW-Authenticate: Bearer; token with 2 chars changed -> 401Decoder: NimbusJwtDecoder.withSecretKey(key).macAlgorithm(MacAlgorithm.HS256).build(), plus an iss validator. Other languages: Node.js uses jose with algorithms: ["HS256"]; Go uses golang-jwt with WithValidMethods.
Spring Security 7: FACTOR_* authorities
Since Security 7 (Boot 4), each authentication method adds a "factor" authority: password login adds FACTOR_PASSWORD, bearer tokens add FACTOR_BEARER. It's the groundwork for MFA.
When signing a token, don't dump all of getAuthorities() into the roles claim, or the token carries FACTOR_PASSWORD. Keep only authorities starting with ROLE_. Identity comes from authentication.getName(); there is no getEmail().
4. Working with AI
Give the AI: integration tests for expired tokens (inject a Clock), alg: none, a foreign issuer, wrong passwords.
Check in AI-written code:
- No
OncePerRequestFilterparsing JWTs by hand. - The decoder pins the algorithm and checks
iss; the secret comes from the environment, ≥ 32 bytes. - Claims hold only
sub,rolesand lifetimes; no passwords, no PII. - The chain ends with
anyRequest().denyAll()orauthenticated(). - 401/403 return ProblemDetail via the entry point and access denied handler, including inside
oauth2ResourceServer.
5. Exercises
Exercise 1: Roles ignored
The token has "roles": ["HR"], the endpoint uses hasRole("HR"), yet every request gets 403. The AI suggests changing the claim to "scope": "HR" and using hasAuthority("SCOPE_HR"). How do you fix it?
Solution to Exercise 1
By default the resource server reads only scope/scp and adds the SCOPE_ prefix, so roles is ignored. The AI's fix works but mixes concepts: a scope is what a user delegates to a client, a role is what the user may do. With a real IdP, SCOPE_HR gets mixed up with real scopes.
Fix: a JwtGrantedAuthoritiesConverter with setAuthoritiesClaimName("roles") and setAuthorityPrefix("ROLE_"), wired through a JwtAuthenticationConverter.
Exercise 2: 401 without JSON
The team writes a @RestControllerAdvice catching AuthenticationException to return JSON. Calling the API with no token still returns the default body, not a ProblemDetail. Why, and how do you fix it?
Solution to Exercise 2
Authentication errors happen in filters, before the DispatcherServlet, so the controller advice never sees them. Write an AuthenticationEntryPoint (401, header WWW-Authenticate: Bearer) and an AccessDeniedHandler (403) that return application/problem+json. Attach them to both oauth2ResourceServer(...) (bad token) and exceptionHandling(...) (no token). Don't put the detailed reason (expired, bad signature) in the body; server logs are enough.
Summary
- A separate chain for
/api/**: stateless, CSRF off only because the token is in a header. - Use
oauth2ResourceServer().jwt(), never a hand-written filter. - Decoder: pinned algorithm,
isscheck, key ≥ 256 bits. - A
rolesclaim needs aJwtAuthenticationConverter. - 401/403 belong in the entry point and access denied handler, not in controller advice.
Read more: Authentication: sessions, cookies and JWT.
Practice interview questions on this topic
- How do you design authentication and authorization for a microservices system?
- What is the structure of a JWT, and how does Spring Security's OAuth2 Resource Server process one?
- How does the Spring Security filter chain work, and why can't @RestControllerAdvice catch token errors?
- How do you implement JWT authentication and authorization in Spring Security end to end?
- What must a resource server check when verifying a JWT, and when is self-issued HS256 enough versus an IdP?
- How does CSRF work, and when is it okay to disable CSRF in Spring Security?
Comments
Community rules