Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To make Spring Security stateless, configure a SecurityFilterChain with SessionCreationPolicy.STATELESS. For a REST API that accepts JWT bearer tokens, enable OAuth 2.0 Resource Server JWT support so each request is authenticated from its token rather than a server-side session.

Configure Spring Security not to use sessions

Use a SecurityFilterChain bean and set the session creation policy to STATELESS. The example permits requests under /public/**, requires authentication elsewhere, and enables JWT bearer-token authentication.

@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        .sessionManagement(session -> session
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        )
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/public/**").permitAll()
            .anyRequest().authenticated()
        )
        .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()));
    return http.build();
}

Spring Security documents that SessionCreationPolicy.STATELESS uses NullSecurityContextRepository and does not save the request in an HTTP session. See Spring Security session management.

Enable JWT validation

Include Spring Security OAuth 2.0 Resource Server and JOSE support in the application. Configure the issuer URI for your identity provider in application.yml:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: https://idp.example.com/issuer

With issuer-uri, Spring Security can discover provider metadata and the JWK Set URI. The resource server validates the JWT signature and checks the issuer (iss) and time claims (exp and nbf). Scopes are mapped to authorities prefixed with SCOPE_. The configuration and validation flow are covered in the Spring Security JWT resource-server documentation.

If metadata discovery is unavailable, or the application must start without depending on discovery, configure the JWK Set URI directly instead. A direct JWK URI changes how keys are located; it does not remove the need to validate tokens and their claims.

What happens on each request

  1. The client sends an Authorization: Bearer <token> header.
  2. The resource-server filter passes the token to JwtAuthenticationProvider.
  3. The provider decodes the token, verifies its signature, and validates its claims.
  4. Spring creates a JwtAuthenticationToken and places it in SecurityContextHolder.
  5. Spring evaluates the authorization rules using the resulting authorities.

This is request authentication: Spring uses the bearer token to establish the security context for the current request, rather than persisting that context in a session. The official documentation states that the authentication filter sets the returned JwtAuthenticationToken on SecurityContextHolder.

Choose the right session policy

Policy Session behavior When it fits
STATELESS Spring Security neither creates nor uses an HTTP session to obtain the security context; requests are not saved in a session. Bearer-token APIs where each request carries its authentication credentials.
NEVER Spring Security does not create a session for the security context, but it can use an existing session. Request caching can also create a session unless separately prevented. Only when reuse of an existing session is intended and session creation by other features is addressed.

For a genuinely session-less security context, choose STATELESS, not NEVER. These policies control Spring Security’s session behavior; application code or other components can still create sessions for unrelated purposes.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why a JSESSIONID may still appear

STATELESS prevents Spring Security from creating or using an HTTP session for its security context. It does not guarantee that no part of the application will ever create a session. Check whether application code, another framework feature, or a component outside the security context is using HttpSession. Also distinguish a cookie that is merely present on an incoming request from a new session created by the server.

When custom code establishes a SecurityContext and expects it to persist across requests, it must save that context through the configured SecurityContextRepository. That persistence is deliberately at odds with a session-less security context; use a suitable repository only if persistence is actually required. Spring documents security context persistence and repositories, including NullSecurityContextRepository when the context must not be associated with an HTTP session.

JWT security decisions that statelessness does not solve

  • Token lifetime: Set an appropriate expiration and account for the impact of a token remaining usable until expiry.
  • Issuer and audience: Validate the intended issuer; validate the audience where the API’s token design requires it.
  • Signing keys: Plan how keys are discovered and rotated, and ensure the resource server can handle key changes safely.
  • Transport: Send bearer tokens only over HTTPS.
  • Authorization: Authentication establishes who or what presented a valid token; define authorization rules that limit access to the right endpoints and operations.
  • CSRF: Make the decision based on how credentials are transported and how the client works. Statelessness alone does not determine whether CSRF protection is appropriate.
  • Logout and revocation: A self-contained JWT is generally validated from its claims and signature on each request. Decide how your system handles logout or revocation before expiry rather than assuming a server session will invalidate it.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

When JWT is not the only option

Stateless session policy and token format are separate choices. Spring Security’s resource-server support can validate bearer credentials without persisting the security context in an HTTP session; a JWT uses locally verifiable claims and discovered or configured signing keys, while opaque-token validation relies on an authorization server to validate the token. Choose between them based on authorization-server availability, key discovery and rotation, claim validation, authority mapping, and the revocation or logout behavior your system needs.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.