A bearer-token API should authenticate each call independently and should not rely on a browser session or redirect cache.
Spring Security stateless APIs: remove session and saved-request assumptions
A stateless boundary
A receipt endpoint receives a bearer token on every request. SessionCreationPolicy.STATELESS tells Spring Security not to use an HTTP session to obtain the SecurityContext. It also changes the saved-request behavior used by browser login flows. A client that expects an HTML redirect to a login page is using the wrong API contract. Return an authentication challenge or error response, then let the client retry with a valid token. 401 versus 403 should remain distinguishable.
Keep browser and API rules separate
A sibling operator console may still use a session, a login redirect and CSRF protection. Put that browser flow in its own chain instead of disabling sessions or CSRF globally. Stateless does not mean every dependency is stateless: an opaque-token introspection call, a rate limiter and a tenant lookup still have network and cache state. It means the API does not use a login session as its authentication source.
Verify the actual response
Send an unauthenticated GET and POST, then a valid bearer request, then another request without the token. Confirm the final call is unauthorized and that the API did not issue an application session cookie. Inspect Location headers to ensure no HTML login redirect escaped into the API. Include a cross-origin browser request in this test plan; CORS preflight has separate handling from authentication.
Implementation contract
http.securityMatcher("/api/**")
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.requestCache(cache -> cache.disable())
.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
.oauth2ResourceServer(oauth -> oauth.jwt(Customizer.withDefaults()));Cost and verification
Per-request token verification adds CPU and possibly key-cache work; it avoids session storage and replication. A remote token check adds network latency unless its bounded cache policy is explicit.
Common Mistakes
- Do not expect a previous bearer request to authenticate the next request without a token.
- Do not disable session behavior on a separate browser-login chain.
- Do not return a login-page redirect from a JSON API.
Read next
Spring Security multiple filter chains: match the whole request surface, Spring Security JWT resource server: validate trust before checking scope, Spring Security 401 versus 403: authentication and access are separate failures, Spring Security CSRF: protect cookie-authenticated writes, Spring Security CORS preflight: evaluate origin before authentication.
