Sub topic 6
Running statelessly: session creation policy
This chapter explains how Spring Security decides whether to create an HTTP session, what SessionCreationPolicy.STATELESS changes, and which mistakes show up when you switch a REST API to stateless operation. It assumes you can write a SecurityFilterChain bean (covered earlier), that you know what a SecurityContext is, and that you understand HTTP headers and cookies at a basic level.
Why sessions matter for security
A classic server-rendered web app logs a user in once. The server then remembers that user in an HTTP session, which is a server-side map identified by a cookie named JSESSIONID. On each later request the browser sends the cookie, and Spring Security restores the user's Authentication from the session.
A REST API usually works differently. Each request carries its own proof of identity, such as an Authorization header with HTTP Basic credentials or a JWT bearer token. The server needs nothing from earlier requests. This is called stateless operation.
Stateless operation has practical benefits:
- Any server instance can handle any request, so you do not need sticky sessions or a shared session store.
- There is no server-side session memory to grow or expire.
- Cookie-based session fixation attacks no longer apply, because there is no session cookie to fix.
It also has costs. The server re-authenticates on every request, which is cheap for a signed JWT but can be expensive for BCrypt-hashed Basic credentials. You also cannot revoke a login by deleting a session. Chapter-level decisions about tokens come later; here the focus is the session setting itself.
How Spring Security uses the session
Two pieces of the filter chain interact with the session.
SecurityContextHolderFilterloads theSecurityContextat the start of a request. By default it reads it from the session throughHttpSessionSecurityContextRepository.- After authentication succeeds, the context is saved so the next request can find it. With the default configuration this save writes to the session, creating one if needed.
If you do nothing, the default policy is IF_REQUIRED: Spring Security creates a session only when something needs one. A successful form login or HTTP Basic authentication counts, so a Basic-protected API quietly starts handing out JSESSIONID cookies. Clients that keep cookies then stop sending credentials, and the API behaves statefully without anyone deciding that.
The four policies
SessionCreationPolicy has four values.
| Policy | Spring Security creates a session | Spring Security uses an existing session |
|---|---|---|
| `ALWAYS` | Always | Yes |
| `IF_REQUIRED` (default) | Only when needed | Yes |
| `NEVER` | Never | Yes, if another part of the app created one |
| `STATELESS` | Never | No |
The difference between NEVER and STATELESS is the one people miss. NEVER means Spring Security will not create a session, but it will still read a security context out of one that already exists. STATELESS means Spring Security will not use sessions at all, and it ignores any existing one for security purposes.
Configuring STATELESS
You set the policy in the sessionManagement customizer. This is the configuration from the chain you built earlier, shown here with the relevant part isolated:
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 statelessApi(HttpSecurity http) throws Exception {
http
.sessionManagement(s -> s
.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults());
return http.build();
}
}With this in place, Spring Security replaces the session-backed repository with a RequestAttributeSecurityContextRepository. The SecurityContext lives only for the duration of a single request. It is cleared when the request ends.
You can check the result with curl. Without the policy, the response to an authenticated request includes a Set-Cookie: JSESSIONID=... header. With it, that header is absent:
curl -i -u alice:change-me http://localhost:8080/api/ordersIf you still see JSESSIONID after setting STATELESS, something other than Spring Security is creating the session. See the gotchas below.
What changes when you go stateless
Switching the policy affects other parts of the configuration. Review each of these.
Every request must carry credentials
A client cannot log in once and reuse a cookie. Each call needs the Authorization header. For HTTP Basic, that means the password is checked on every call, which is the reason BCrypt's deliberate slowness becomes a throughput concern. For JWT bearer tokens, the cost is a signature check, which is fast.
CSRF protection depends on sessions
Cross-site request forgery works because browsers attach cookies automatically. A stateless API that authenticates only through a header the browser does not attach on its own is not exposed in the same way. This is the reasoning behind disabling CSRF for such an API, covered in the next chapter. The reasoning holds only if no cookie carries authentication. If you keep a session or any auth cookie, keep CSRF protection.
Form login and remember-me don't fit
Form login depends on a session to remember the result. rememberMe depends on a cookie. Neither is meaningful under STATELESS. Use Basic or a bearer token instead.
Authentication failures become unambiguous
With a session, a request that omits credentials may still succeed because the cookie restores the user. Under STATELESS, a request with no credentials always gets 401 Unauthorized. Tests that relied on the session carrying identity between calls will fail, which is a good sign that the policy is working.
Gotchas and failure modes
Something else creates a session
STATELESS governs Spring Security only. Your own code can still call request.getSession(), and a few framework features create sessions as well. Common causes include:
- A controller or filter that calls
HttpServletRequest.getSession()orgetSession(true). - A controller method with an
HttpSessionparameter, because Spring MVC creates the session to inject it. @SessionAttributeson a controller.- Error pages in some servlet container setups.
Spring Security will not use that session for authentication, so you are not logged in through it, but the cookie still goes out. Search your code for HttpSession and getSession when you see an unexpected JSESSIONID.
An existing session is ignored, not invalidated
Switching a running app to STATELESS does not destroy sessions that clients already hold. Spring Security ignores them for authentication. The container expires them on its normal timeout.
Anonymous requests get a context too
Even without a session, Spring Security populates the SecurityContext for each request. For anonymous callers this is an AnonymousAuthenticationToken. Do not treat a non-null Authentication as proof of login. Check isAuthenticated() and that the principal is not anonymous.
Using the context across threads
Because the context lives in a thread-local for the request, work you hand off to another thread does not see it unless you propagate it. This is a general Spring Security concern, but stateless APIs notice it because there is no session to fall back on.
Saving the context manually
If you write a custom login endpoint, you cannot rely on the session to persist the result under STATELESS. Setting SecurityContextHolder.getContext().setAuthentication(auth) only affects the current request, which is the intended behavior. Do not try to work around it by creating a session yourself.
Verifying the behavior in a test
You can assert that no session is created. The MockMvc result exposes the request, and you can check the session on it:
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
@SpringBootTest
@AutoConfigureMockMvc
class StatelessSessionTest {
@Autowired
MockMvc mvc;
@Test
void noSessionIsCreated() throws Exception {
MvcResult result = mvc.perform(get("/api/orders")
.with(httpBasic("alice", "change-me")))
.andExpect(status().isOk())
.andReturn();
assertNull(result.getRequest().getSession(false));
}
}getSession(false) returns the existing session or null without creating one, so a null result confirms that nothing created a session during the request. This test assumes the alice user from the earlier chapter and a controller mapped at /api/orders.
Choosing a policy
Use these criteria when deciding.
- Pick
STATELESSfor APIs consumed by mobile apps, other services, or single-page apps that send a token in a header. - Keep
IF_REQUIREDfor server-rendered pages with form login, where a session is the normal way to remember the user. - Use
NEVERonly when another component deliberately owns the session and you want Spring Security to read it without creating one. This is rare. - Avoid
ALWAYSunless a specific feature needs a session on every request. It adds memory cost with no security benefit.
Exercise
A team sets SessionCreationPolicy.STATELESS but still sees a JSESSIONID cookie in responses from one endpoint. Spring Security is not authenticating through that session. Name two likely causes and say how you would find them.
Show answer
Application code is creating the session, not Spring Security. Likely causes are a controller method that takes an HttpSession parameter or calls request.getSession(), and a controller annotated with @SessionAttributes. Search the code for HttpSession, getSession, and @SessionAttributes, then confirm with a test that calls the endpoint and asserts request.getSession(false) is null.
Exercise
What is the difference between NEVER and STATELESS, and why does it matter if a client still holds an old JSESSIONID?
Show answer
NEVER stops Spring Security from creating a session but still reads a security context from an existing one. STATELESS never uses a session for the security context. With NEVER, an old JSESSIONID could still authenticate the client. With STATELESS, the cookie is ignored for authentication and the client must send credentials on every request.