Sub topic 6
Running statelessly: session creation policy
This chapter assumes you can build Spring Boot REST controllers, define @Bean methods, and read a SecurityFilterChain from the previous chapter. You should also know that HTTP is stateless and that a session is server-side memory tied to a cookie.
What a session does by default
When a user logs in through a browser form, Spring Security stores the SecurityContext (the object that holds the authenticated user) in the HTTP session. The server sends back a JSESSIONID cookie. On the next request the browser returns the cookie, and Spring Security restores the user from the session. The client does not need to send credentials again.
A REST API usually works differently. Each request carries its own proof of identity, such as an Authorization header with Basic credentials or a bearer token. A server session adds nothing, and it costs memory. It also makes horizontal scaling harder, because the next request may reach a different instance that does not hold the session.
Setting the policy
You control this with sessionManagement and a SessionCreationPolicy.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class StatelessConfig {
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.sessionManagement(s -> s
.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults());
return http.build();
}
}The four policies differ in how they treat the session:
| Policy | Behavior |
|---|---|
| `ALWAYS` | Creates a session if none exists. |
| `IF_REQUIRED` | The default. Creates a session only when something needs one. |
| `NEVER` | Never creates a session, but uses one if the application already made it. |
| `STATELESS` | Never creates or uses a session to store the `SecurityContext`. |
With STATELESS, Spring Security saves nothing between requests. Each request is authenticated from scratch, and the SecurityContext is cleared when the request ends.
Consequences of going stateless
Three things change when you choose STATELESS.
- Every request must authenticate. With HTTP Basic, the server verifies the password on every call. BCrypt is deliberately slow, so this costs CPU. Bearer tokens avoid that cost because validating a signature is cheap, which is one reason the later JWT chapter matters.
- No login state to log out of. There is nothing to invalidate on the server. With tokens, you shorten their lifetime instead.
- CSRF reasoning changes. CSRF attacks rely on the browser attaching a cookie automatically. If your API has no session cookie, that attack path is gone. The next chapter covers when it is safe to disable CSRF protection.
Common errors
- Setting
STATELESSbut still seeingJSESSIONID. Spring Security no longer creates the session, but something else may. A controller that callsrequest.getSession(), or a view layer, can still create one. Search your code for those calls. - Expecting a login to persist. If a custom login endpoint authenticates a user and sets the
SecurityContext, the next request will be anonymous. UnderSTATELESSyou must return a token and have the client send it each time. - Using
STATELESSon a form-login application. A browser form flow depends on the session. ChooseIF_REQUIREDfor that kind of app.
You can check the behavior with a quick request. A call with valid credentials returns 200 and no Set-Cookie header:
curl -i -u alice:change-me http://localhost:8080/api/ordersIf a Set-Cookie: JSESSIONID=... header appears, a session was created somewhere.
Exercise
A developer sets SessionCreationPolicy.STATELESS and uses HTTP Basic. A load test shows high CPU on the login path. Why does this happen, and what is one way to reduce it?
Show answer
Without a session, the server verifies the password on every request, and BCrypt is intentionally slow. Switching to bearer tokens (such as JWTs) means each request needs only a signature check, which is much cheaper.
Exercise
After the policy is set to STATELESS, a response still carries a JSESSIONID cookie. Name one likely cause.
Show answer
Application code, such as a controller calling request.getSession(), created the session. STATELESS only stops Spring Security from using a session for the SecurityContext.