Sessions and the STATELESS policy

Spring Security · lesson 7 of 31 · 3 min read

Control when a session is created, protect it from fixation, and know what STATELESS really does.

Open this lesson in the learning hub

Key points

  • SessionCreationPolicy.STATELESS stops Spring Security creating or reading an HttpSession. Requests stand alone.
  • STATELESS does not disable sessions app-wide. Other code can still create one — it just will not carry your identity.
  • With sessions on, the session id is rotated at login. That is session fixation protection; leave it enabled.
  • maximumSessions(1) caps concurrent logins per user. Handy for admin consoles and shared accounts.
  • Since Spring Security 6 the context is no longer auto-saved. Log a user in manually and you must save it to the repository yourself.

Example

// Token API: no session at all
http.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS));

// Session app: rotate the id at login, one live session per user
http.sessionManagement(s -> s
    .sessionFixation(f -> f.changeSessionId())
    .maximumSessions(1)
    .maxSessionsPreventsLogin(false));   // new login wins, old one expires

// Manual login in Spring Security 6 — saving the context is on you
SecurityContext ctx = SecurityContextHolder.createEmptyContext();
ctx.setAuthentication(authentication);
SecurityContextHolder.setContext(ctx);
new HttpSessionSecurityContextRepository().saveContext(ctx, request, response);

STATELESS means "security ignores sessions", not "sessions are impossible".

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Spring Security course, and every lesson in it is listed on the Spring Security contents page.