Spring Security for REST APIs series: 1. JWT with the resource server · 2. Refresh tokens and authorization
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 filter chain for a stateless API
Key idea: Spring Security is a series of servlet filters running before the DispatcherServlet. For an API you declare a dedicated chain for /api/**: no session, no CSRF, bearer-token authentication.
The stateful version for a server-rendered web app (DelegatingFilterProxy, FilterChainProxy, form login, session and CSRF) is in form login with Spring Security; this post covers only what differs.
flowchart LR
R[Request] --> C[CorsFilter]
C --> B[BearerTokenAuthenticationFilter]
B --> E[ExceptionTranslationFilter]
E --> A[AuthorizationFilter]
A --> D[DispatcherServlet and controller]
B -.bad token.-> P401[401 via AuthenticationEntryPoint]
A -.missing permission.-> P403[403 via AccessDeniedHandler]
BearerTokenAuthenticationFilter: takes the token from the header, calls theJwtDecoder, puts anAuthenticationinto theSecurityContext.ExceptionTranslationFilter: catches exceptions from the filters after it. Not authenticated → 401; authenticated but not allowed → 403.AuthorizationFilter: checks theauthorizeHttpRequestsrules through anAuthorizationManager.
The lab’s real configuration (CORS and beans further down):
@Bean
SecurityFilterChain api(HttpSecurity http, PermissionAuthorizationManager permissionCheck,
ProblemJsonSecurityHandlers problems) throws Exception {
http.securityMatcher("/api/**")
.csrf(csrf -> csrf.disable()) // access token travels in a header, not a cookie
.cors(Customizer.withDefaults())
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.requestMatchers(HttpMethod.POST, "/api/v1/auth/login", "/api/v1/auth/refresh").permitAll()
.requestMatchers(HttpMethod.POST, "/api/v1/auth/logout").authenticated()
.requestMatchers("/api/v1/**").access(permissionCheck) // part 2
.anyRequest().denyAll()) // deny by default
.oauth2ResourceServer(rs -> rs
.jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter()))
.authenticationEntryPoint(problems)
.accessDeniedHandler(problems))
.exceptionHandling(e -> e.authenticationEntryPoint(problems).accessDeniedHandler(problems));
return http.build();
}
The final anyRequest().denyAll() is deny-by-default: a new endpoint whose rule you forgot returns 403 instead of being wide open.
2. Resource server, authorization server or an external IdP
Key idea: a resource server only validates tokens; an authorization server issues them under the OAuth2 standard. A single API can issue its own HS256 JWTs; with many services, SSO or MFA, use an IdP (Keycloak, Auth0, Cognito) with RS256 + JWKS.
| Option | Fits when | Cost |
|---|---|---|
| Self-issued HS256 JWT + resource server | One API, your own frontend | You own login, refresh, keys; every verifying service holds the same secret |
| Spring Authorization Server | You must be an OAuth2 provider for third parties | Lots of code and flows, hard to operate |
| External IdP (Keycloak…) | Many services, SSO, MFA, social login | One more system; the API only needs issuer-uri |
With HS256, whoever holds the secret can sign tokens. Once two or more services verify tokens, move to asymmetric keys (RS256/ES256): the IdP keeps the private key, services fetch public keys from the JWKS. JWKS setup and the aud check are in section 7 of the authentication post.
Don’t hand-write a OncePerRequestFilter that parses JWTs like many tutorials do: the spring-boot-starter-security-oauth2-resource-server starter already extracts the header, verifies the signature and exp/nbf, and answers 401 with an RFC 6750 WWW-Authenticate header.
3. Storing passwords and loading users
Key idea: use DelegatingPasswordEncoder (hashes prefixed with {bcrypt}) so you can switch algorithms later without breaking old hashes; the UserDetailsService loads a user by email and fails exactly like a wrong password.
@Bean
PasswordEncoder passwordEncoder() {
// {bcrypt}$2a$10$... : the prefix lets you migrate to argon2 later
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
- BCrypt only reads the first 72 bytes of a password. The DTO caps it with
@Size(max = 72)so users don’t think the rest matters. - Why BCrypt/Argon2 and which cost: see storing passwords and encrypting personal data.
@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String email) {
var u = users.findByEmailIgnoreCase(email) // @EntityGraph loads roles too
.orElseThrow(() -> new UsernameNotFoundException("Bad credentials"));
return User.withUsername(u.getEmail())
.password(u.getPassword())
.roles(u.getRoles().stream().map(r -> r.getName()).toArray(String[]::new)) // -> ROLE_xxx
.build();
}
DaoAuthenticationProvider already hides UsernameNotFoundException behind BadCredentialsException by default, so attackers can’t probe which emails exist. Keep the exception message neutral anyway, in case someone logs it.
4. The login endpoint: AuthenticationManager, then sign a JWT
Key idea: the controller never compares passwords itself; it hands email + password to the AuthenticationManager, gets back an authenticated Authentication, then asks the JwtService to sign an access token.
sequenceDiagram
participant SPA
participant API as AuthController
participant AM as AuthenticationManager
participant DB
SPA->>API: POST /api/v1/auth/login {email, password}
API->>AM: authenticate(unauthenticated token)
AM->>DB: loadUserByUsername(email)
AM-->>API: Authentication (ROLE_ADMIN, FACTOR_PASSWORD)
API-->>SPA: 200 {accessToken} + Set-Cookie refresh_token
@PostMapping("/login")
public ResponseEntity<ApiResponse<TokenResponse>> login(@Valid @RequestBody LoginRequest req) {
Authentication auth = authManager.authenticate(
UsernamePasswordAuthenticationToken.unauthenticated(req.email(), req.password()));
var user = users.findByEmailIgnoreCase(auth.getName()).orElseThrow();
// Spring Security 7 also adds FACTOR_PASSWORD; keep only ROLE_ authorities in the token.
var roles = auth.getAuthorities().stream().map(a -> a.getAuthority())
.filter(a -> a.startsWith("ROLE_")).map(a -> a.substring(5)).toList();
return withTokens(jwtService.issueAccessToken(user.getEmail(), roles), refreshTokens.issue(user));
}
The AuthenticationManager bean is declared explicitly, because Boot doesn’t expose one for controllers to inject:
@Bean
AuthenticationManager authenticationManager(UserDetailsService uds, PasswordEncoder encoder) {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider(uds);
provider.setPasswordEncoder(encoder);
return new ProviderManager(provider);
}
A wrong password throws BadCredentialsException; an @ExceptionHandler in the controller turns it into a 401 ProblemDetail “Invalid email or password”. That handler works because the error happens inside the controller, not in a filter.
5. Signing and verifying tokens
Key idea: encoder and decoder share one SecretKey of at least 256 bits read from an environment variable; the decoder must pin HS256 and check iss, never trusting the algorithm written in the token header.
public String issueAccessToken(String email, Collection<String> roles) {
Instant now = Instant.now();
JwtClaimsSet claims = JwtClaimsSet.builder()
.issuer(props.issuer()).subject(email)
.issuedAt(now).expiresAt(now.plus(props.accessTtl())) // 15 minutes
.claim("roles", List.copyOf(roles)) // no password, no PII
.build();
JwsHeader header = JwsHeader.with(MacAlgorithm.HS256).build();
return encoder.encode(JwtEncoderParameters.from(header, claims)).getTokenValue();
}
SecretKey, JwtEncoder, JwtDecoder beans and configuration
@Bean
SecretKey jwtKey(JwtProperties props) {
byte[] bytes = Base64.getDecoder().decode(props.secret());
if (bytes.length < 32) throw new IllegalStateException("HS256 key must be at least 256 bits");
return new SecretKeySpec(bytes, "HmacSHA256");
}
@Bean
JwtEncoder jwtEncoder(SecretKey jwtKey) {
return new NimbusJwtEncoder(new ImmutableSecret<>(jwtKey));
}
@Bean
JwtDecoder jwtDecoder(SecretKey jwtKey, JwtProperties props) {
NimbusJwtDecoder decoder = NimbusJwtDecoder.withSecretKey(jwtKey)
.macAlgorithm(MacAlgorithm.HS256) // pin the algorithm
.build();
decoder.setJwtValidator(JwtValidators.createDefaultWithIssuer(props.issuer())); // exp, nbf, iss
return decoder;
}
# Dev only; shared environments read it from an env var / secret manager
app.jwt.secret=${JWT_SECRET:ZGV2LW9ubHktc2VjcmV0LWRldi1vbmx5LXNlY3JldC0zMmJ5dGVzISE=}
app.jwt.issuer=https://hr.example.dev
app.jwt.access-ttl=15m
app.jwt.refresh-ttl=7d
JwtProperties is a record with @ConfigurationProperties(prefix = "app.jwt"), Duration for TTLs, and it throws at startup if the secret is missing: an app that refuses to start beats one running with an empty secret.
Three things the decoder must do, which the lab checks with a test (a token with its last two characters changed → 401):
- Pin the algorithm: blocks algorithm swapping (RS256 → HS256 with the public key as secret, or
alg: none). - Check
iss(andaudonce several APIs exist): a token from another system is useless here. - Use a long enough key: HMAC-SHA256 needs ≥ 256 bits; a secret like “123456” can be brute-forced offline from any single token.
6. From a roles claim to ROLE_xxx
Key idea: by default the resource server reads the scope/scp claim and creates SCOPE_xxx authorities. Our tokens carry roles, so a JwtAuthenticationConverter is needed to get ROLE_xxx for hasRole.
static JwtAuthenticationConverter jwtAuthenticationConverter() {
JwtGrantedAuthoritiesConverter roles = new JwtGrantedAuthoritiesConverter();
roles.setAuthoritiesClaimName("roles"); // claim "roles": ["HR"]
roles.setAuthorityPrefix("ROLE_"); // -> ROLE_HR
JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
converter.setJwtGrantedAuthoritiesConverter(roles);
return converter;
}
Don’t put the full permission list into the token: it bloats, and a permission change waits for the token to expire. The lab keeps only coarse roles; permissions are looked up on the server (part 2).
7. 401 and 403 as JSON
Key idea: authentication and URL-level authorization errors are raised in filters, before the DispatcherServlet, so @RestControllerAdvice never sees them. Write an AuthenticationEntryPoint (401) and an AccessDeniedHandler (403) that return the same ProblemDetail format.
@Override
public void commence(HttpServletRequest req, HttpServletResponse res, AuthenticationException ex) throws IOException {
res.setHeader("WWW-Authenticate", "Bearer");
write(res, 401, "Unauthorized", "Missing, invalid or expired access token");
}
@Override
public void handle(HttpServletRequest req, HttpServletResponse res, AccessDeniedException ex) throws IOException {
write(res, 403, "Forbidden", "You do not have permission for " + req.getMethod() + " " + req.getRequestURI());
}
Register the handler on both oauth2ResourceServer(...) and exceptionHandling(...): the first catches bad tokens, the second catches requests with no token at all. The lab’s test confirms: no token → 401, WWW-Authenticate: Bearer, content type application/problem+json. The API’s shared error format and ProblemDetail: see error handling in Spring Boot.
Don’t put the precise reason (expired, bad signature) into the 401 body: server logs are enough, the client only needs to know it should refresh or log in again.
8. CORS for an SPA and where the access token lives
Key idea: an SPA on another origin needs CORS for that exact origin, the Authorization header allowed and allowCredentials(true) (to send the refresh cookie). The access token lives in JavaScript memory, not in localStorage.
CorsConfiguration cfg = new CorsConfiguration();
cfg.setAllowedOrigins(origins); // exact origins, never "*" with credentials
cfg.setAllowedMethods(List.of("GET", "POST", "PUT", "PATCH", "DELETE"));
cfg.setAllowedHeaders(List.of("Authorization", "Content-Type"));
cfg.setAllowCredentials(true);
cfg.setMaxAge(3600L);
.cors(Customizer.withDefaults()) in the chain lets the OPTIONS preflight be answered before a token is demanded. Without it the browser reports a CORS error while Postman still works (explained in web and HTTP).
9. The lab: what was run
Key idea: the HR API lab (Spring Boot 4.0.3, JDK 21, H2) runs 29 tests with mvn test: 28 pass, 1 skipped (the Testcontainers PostgreSQL test; this machine had no running Docker engine).
- App started with the
devprofile:POST /api/v1/auth/loginreturned 200 withSet-Cookie: refresh_token=...; Path=/api/v1/auth; HttpOnly; Secure; SameSite=Strict. GET /api/v1/users/1without a token → 401,WWW-Authenticate: Bearer.- Integration tests (
@SpringBootTest+ MockMvc): wrong password → 401, tampered token → 401, token from login can call the API.
What a senior would change in this lab
- Many services: move to RS256/ES256 with JWKS and rotate keys by
kid; HS256 forces every service to hold a key that can sign tokens. - Check
aud: add aJwtClaimValidatorfor the audience when more than one API shares an issuer. - Rate-limit the login endpoint (per IP and per email) and lock out temporarily after repeated failures; BCrypt is slow on purpose, which also makes it a DoS target.
- Audit-log successful and failed logins, never the password or token.
- Don’t issue tokens yourself if the organisation already has an IdP: the API only needs
spring.security.oauth2.resourceserver.jwt.issuer-uri. - Test security with tests:
alg: none, expired token (inject aClock), foreign issuer should all have automated tests.
Remember
- Draw the filter order from request to controller, and point at where 401 and where 403 are produced.
- Explain why disabling CSRF is safe for a bearer-header chain, and when it stops being safe.
- Know the three things a
JwtDecodermust check and why HS256 is a poor fit for many services. - Configure a
JwtAuthenticationConvertersohasRoleworks with arolesclaim. - Explain why
@RestControllerAdvicecannot catch filter-level 401/403 errors.
Interview questions
Junior
Is a JWT encrypted? Should the payload contain email or phone number?
No, a normal JWT (JWS) is only signed; the payload is Base64url anyone can read. Keep only minimal identity in it.
The signature prevents tampering, not reading. Email as sub is acceptable in an internal system, but never passwords, card numbers or sensitive personal data. To hide content, use JWE or an opaque token looked up on the server.
What is the difference between 401 and 403 in Spring Security?
401: you could not be authenticated (no token, bad token, expired). 403: we know who you are, but you lack permission.
ExceptionTranslationFilter decides: an AuthenticationException goes to the AuthenticationEntryPoint (401); an AccessDeniedException for an authenticated user goes to the AccessDeniedHandler (403).
Mid
Why can an API using JWTs in a header disable CSRF?
Because CSRF relies on the browser attaching cookies automatically; the Authorization header is never sent automatically.
A malicious page can’t read the token in the SPA’s memory, so it can’t forge the request. The condition is that no credential travels as a cookie on that chain. The refresh endpoint, which does use a cookie, is protected by SameSite=Strict, a narrow path and strict CORS.
Why doesn’t @RestControllerAdvice catch an expired-token error?
Because the error happens in a security filter, before the DispatcherServlet; controller advice only sees exceptions thrown while MVC handles the request.
For a consistent format, install an AuthenticationEntryPoint and an AccessDeniedHandler that write ProblemDetail. Conversely, an AccessDeniedException from @PreAuthorize is thrown inside the controller call, so the advice does see it, and a catch-all handler can turn it into a 500.
Which claim does the default resource server configuration turn into authorities?
The scope (or scp) claim, split on spaces and prefixed with SCOPE_.
To use hasRole('ADMIN') with a roles claim, configure a JwtGrantedAuthoritiesConverter that reads roles with the ROLE_ prefix and plug it into a JwtAuthenticationConverter. Don’t put roles into scope: scopes are what a user delegates to a client.
Senior
When is a self-issued HS256 JWT enough, and when should you use an IdP?
One API with your own frontend: a self-issued HS256 token is enough. Many services, SSO, MFA or third parties: use an IdP with asymmetric keys.
With HS256, every verifier can also sign, so leaking the secret in one service compromises all of them. An IdP keeps the private key, services only need public keys via JWKS, and keys rotate by kid without redeploys. The price is one more system to run and a dependency at login time.
A colleague puts all of getAuthorities() into the token’s claims on Spring Security 7. What’s wrong?
The token will contain FACTOR_PASSWORD (and possibly other non-role authorities), so claim-based permissions go wrong and the token carries noise.
Security 7 adds factor authorities for MFA. Select only what the token contract needs (here, roles without the ROLE_ prefix) and add a test asserting the claim content.
List what a JwtDecoder must check in a production system.
The signature with a pinned algorithm, exp/nbf with a small clock skew, iss, aud, and the key length.
Never take the algorithm from the token header (alg: none or RS256-to-HS256 attacks). With JWKS, only accept keys from a trusted issuer. Add an automated test for each broken case.
Useful phrases for interviews
- “Every API request goes through the security filter chain before it reaches a controller.”
- “Our API is a resource server: it validates tokens but never issues them.”
- “We disabled CSRF on that chain because the credential is a bearer header, not a cookie.”
- “The decoder pins HS256 and validates the issuer, so the alg-none trick doesn’t work.”
- “With HS256 the verifying key is also a signing key, which is why we’d move to RS256 and JWKS for several services.”
- “By default the resource server maps scope to SCOPE_ authorities, so we configured a converter for our roles claim.”
- “Filter-level errors never reach the controller advice, so 401 and 403 are written by the entry point and the access-denied handler.”
- “We end the rules with denyAll, so a forgotten endpoint is closed, not open.”
- “The access token stays in memory; the refresh token sits in an HttpOnly cookie.”
Notes based on Hỏi Dân IT course material, rewritten and extended in my own words.