Sub topic 16
Pitfalls: revocation, lifetimes, CORS, and token storage
This chapter assumes you have a working JWT resource server: a SecurityFilterChain with oauth2ResourceServer, a JwtDecoder with issuer and audience checks, and an understanding of exp, iss, and aud. A correctly configured resource server can still be unsafe in practice. The remaining risks come from how long tokens live, whether you can cancel them, which browsers may call your API, and where clients keep tokens.
Revocation: a signed JWT is valid until it expires
A resource server that validates JWTs locally checks the signature and claims and never contacts the authorization server. That is what makes JWTs fast and scalable. It also means the API cannot tell that a token was revoked, a user was disabled, or a password was reset. The token stays valid until exp.
You have four common options. They trade freshness against cost.
| Approach | Revocation delay | Cost |
|---|---|---|
| Short-lived access tokens only | Up to the token lifetime | Clients must refresh often |
| Revoke the refresh token at the authorization server | Up to the access token lifetime | Stops new access tokens, not existing ones |
| Denylist of `jti` values checked in a validator | Near zero | A shared store lookup on each request |
| Opaque tokens with introspection | Near zero (depends on caching) | A network call to the authorization server |
Most systems combine short access tokens with refresh-token revocation. Use introspection or a denylist only for operations where a delay of a few minutes is not acceptable.
A denylist validator
Spring Security lets you add any OAuth2TokenValidator<Jwt> to the decoder. This one rejects tokens whose jti claim is in a revoked set. The Predicate stands in for your shared store, such as Redis.
import java.time.Duration;
import java.util.function.Predicate;
import org.springframework.context.annotation.Bean;
import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtIssuerValidator;
import org.springframework.security.oauth2.jwt.JwtTimestampValidator;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
@Bean
JwtDecoder jwtDecoder(Predicate<String> isRevoked, String issuer) {
NimbusJwtDecoder decoder = NimbusJwtDecoder.withIssuerLocation(issuer).build();
OAuth2TokenValidator<Jwt> notRevoked = jwt ->
jwt.getId() != null && isRevoked.test(jwt.getId())
? OAuth2TokenValidatorResult.failure(
new OAuth2Error("invalid_token", "The token has been revoked", null))
: OAuth2TokenValidatorResult.success();
decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(
new JwtTimestampValidator(Duration.ofSeconds(30)),
new JwtIssuerValidator(issuer),
notRevoked));
return decoder;
}The denylist only needs to hold entries until the token's exp, so you can set an expiry on each stored entry. A denylist also brings back a per-request lookup, which removes part of the benefit of stateless JWTs. Make that choice on purpose.
Lifetimes: choosing `exp` and clock skew
Access token lifetime is set at the authorization server, not in your API. Your API still has to decide how much it trusts a long lifetime.
- Short (5 to 15 minutes): limits the damage of a stolen token. Clients need a refresh flow.
- Long (hours or days): simpler for clients, but a leaked token is usable for a long time and revocation is slow.
- Refresh tokens: keep them out of the API's reach. Only the client and the authorization server should handle them. Rotate them on use if the provider supports it.
Clock skew is a related pitfall. Servers' clocks drift, so a token issued a second ago may look as if it was issued in the future (nbf or iat). Spring's default timestamp validator allows 60 seconds of skew. The decoder above narrows this to 30 seconds with JwtTimestampValidator. Do not raise it to minutes to hide a broken clock. Fix time synchronization (NTP) instead.
CORS: browsers call your API from other origins
CORS (Cross-Origin Resource Sharing) is a browser rule. A page served from https://app.example.com may call https://api.example.com only if the API's response headers allow it. Non-browser clients such as curl or other services ignore CORS, so it never replaces authentication.
A common failure looks like this. The browser sends a preflight request first. It is an OPTIONS request that carries no Authorization header. If Spring Security's authorization rules see it before the CORS handling does, it gets a 401, and the browser then blocks the real request. The fix is to enable CORS in the security chain so the CORS filter answers preflights first.
import java.time.Duration;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
// In the filter chain: http.cors(Customizer.withDefaults())
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(List.of("https://app.example.com"));
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
config.setAllowedHeaders(List.of("Authorization", "Content-Type"));
config.setMaxAge(Duration.ofHours(1));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return source;
}Common CORS mistakes:
- Allowing
*as the origin "just to make it work". List the exact origins you trust. - Forgetting
Authorizationin the allowed headers. The browser then rejects the preflight. - Adding
@CrossOriginon controllers while the security chain has nocors()setup. The preflight still fails with 401. - Treating a CORS error as an authentication bug. Check the browser's network tab: a failed
OPTIONSrequest points to CORS.
CSRF and cookies
Bearer tokens sent in the Authorization header are not attached automatically by the browser, so a malicious site cannot make the browser send them. This is why stateless bearer-only APIs usually disable CSRF protection. Spring Security's resource server support already ignores CSRF checks for requests that carry a bearer token.
If you move the token into a cookie, the browser attaches it automatically and CSRF protection becomes necessary again. Do not mix the two models without thinking it through.
Token storage on the client
The API cannot control how clients store tokens, but its design affects the choices clients have. Share this guidance with the teams that build clients.
| Where | Risk | Notes |
|---|---|---|
| `localStorage` or `sessionStorage` | Any script on the page can read it (XSS) | Easy to use, easy to steal from |
| JavaScript memory | Lost on reload, still exposed to XSS while running | Pair with a silent refresh |
| `HttpOnly`, `Secure`, `SameSite` cookie | Scripts cannot read it, but CSRF applies | Best used with a backend-for-frontend (BFF) |
| Mobile keychain or keystore | Depends on device security | Use the platform's secure storage |
A BFF is a small server-side component that performs the OAuth2 login, keeps the tokens on the server, and gives the browser only a session cookie. The browser never sees the JWT. This design is the strongest choice for browser apps, at the cost of one more component to run.
On the API side, keep tokens out of places where they leak:
- Do not accept tokens in query strings. Spring's default resolver reads only the
Authorizationheader unless you enablesetAllowUriQueryParameter, and you should leave it off. URLs end up in logs, proxies, and browser history. - Do not log the
Authorizationheader or full JWTs. Log thesubandjticlaims instead. - Do not put secrets or personal data in the payload. A JWT is signed, not encrypted. Anyone holding it can base64-decode the claims.
A short checklist
- Access tokens are short-lived, and refresh tokens are revoked on logout or compromise.
- The decoder validates timestamps, issuer, and audience, with a small clock skew.
- A revocation path exists (denylist or introspection) for cases where a delay is unacceptable.
- CORS lists exact origins, and
http.cors(...)is enabled so preflights succeed. - Browser clients keep tokens in a BFF session or in memory, not in
localStorage. - Tokens never appear in URLs or logs.
Exercise
Your API validates JWTs locally. An administrator disables a user at the authorization server, but the user's existing access token (15 minutes left) still gets 200 responses. Name two ways to close this gap and one cost of each.
Show answer
Option 1: add a validator that checks the token's jti against a denylist in a shared store such as Redis. Cost: a store lookup on every request, which weakens the stateless benefit of JWTs. Option 2: switch to opaque tokens with introspection, so the authorization server decides on each call. Cost: a network call per request (or a cache that reintroduces a short delay). Shortening the access token lifetime also narrows the gap, at the cost of more refresh traffic.
Exercise
A single-page app on https://app.example.com calls your API. The browser console shows a CORS error, and the network tab shows the OPTIONS request returning 401. What is wrong, and what two changes fix it?
Show answer
The preflight OPTIONS request carries no Authorization header, and the security chain rejects it before CORS handling answers. Enable CORS in the chain with http.cors(Customizer.withDefaults()), and define a CorsConfigurationSource bean that allows the origin https://app.example.com and lists Authorization among the allowed headers.