
# Sessions

After a form login or a single sign-on, the user is kept in the web starter's `HttpSession`, so the next requests are logged in by the session cookie. APIs whose clients send credentials or a token with every request use no session at all. Only a login makes a session: before it, what the chain must remember is kept in cookies.

## Why

A session is server memory tied to a cookie. Making one for every visitor lets anyone fill the server's memory with requests; keeping the same id across a login lets an attacker who planted an id before the login take over the account. The starter makes sessions only at login, changes the id then, and limits how many sessions there are in total and per user.

## Example

```dart
// An API: no session, a token with every request.
@Bean()
@Order(1)
SecurityFilterChain api(HttpSecurity http) => http
    .securityMatcher('/api/**')
    .authorizeHttpRequests((auth) => auth.anyRequest().authenticated())
    .oauth2ResourceServer((s) => s.jwt())
    .sessionManagement((s) => s.sessionCreationPolicy(SessionCreationPolicy.stateless))
    .build();

// Pages: a session after the login, at most 3 per user, a 4th login refused.
@Bean()
@Order(2)
SecurityFilterChain web(HttpSecurity http) => http
    .authorizeHttpRequests((auth) => auth.anyRequest().authenticated())
    .formLogin()
    .sessionManagement((s) => s.maximumSessions(3).maxSessionsPreventsLogin(true))
    .build();
```

## Session management

| Option | Default | Meaning |
|---|---|---|
| `sessionCreationPolicy(policy)` | `ifRequired` | `ifRequired`: a session at login keeps the user. `stateless`: security never uses a session; the user is kept for the current request only, no page is saved for after a login. |
| `sessionFixation(changeSessionId:)` | `true` | Whether a login gives the session a new id. |
| `maximumSessions(n)` | `spring.security.session.maximum-sessions` (10) | The most sessions per user; `-1` for no limit. |
| `maxSessionsPreventsLogin(bool)` | `spring.security.session.max-sessions-prevents-login` (`false`) | Whether a login over the limit is refused instead of ending the user's least recently used session. |
| `sessionRegistry(registry)` | in memory | Where the sessions of each user are counted. |

There is no `always` or `never` policy.

## The limits

- **Per user:** each user holds at most 10 sessions by default. A new login ends the user's least recently used session, or is refused with `maxSessionsPreventsLogin(true)`. Filling the store therefore takes as many accounts as a tenth of its limit. Set it for every chain with sessions in properties (not in Spring Boot), or per chain; a chain's own setting wins. `0` and values below `-1` fail the start.
- **In total:** sessions are limited by the web starter's `server.session.max-sessions` (10 000 by default). When the store is full, expired sessions are removed; if none is, the login is refused with `503`. No live session is removed to make room.

```properties
spring.security.session.maximum-sessions=3
spring.security.session.max-sessions-prevents-login=false
server.session.max-sessions=10000
server.session.timeout=30m
```

Chains without sessions (`stateless`, bearer tokens, HTTP Basic) ignore the per-user limit.

## Before a login: cookies

Spring Security keeps the CSRF token, the page to come back to and the OAuth 2.0 authorization request in the session. Here they are cookies, so clients that are not logged in fill no memory:

| Cookie | Holds | Class |
|---|---|---|
| `XSRF-TOKEN` | The CSRF token, a random value (`HttpOnly`, `SameSite=Lax`). | `CookieCsrfTokenRepository` |
| `REDIRECT_URI` | The page to come back to after a login. | `CookieRequestCache` |
| `OAUTH2_AUTHORIZATION_REQUEST` | The OAuth 2.0 authorization request (`state`, PKCE verifier, `nonce`). | `CookieOAuth2AuthorizationRequestRepository` |

The two signed cookies are read only when their signature, name and expiry are right, and the page to come back to only when it is a path of this site. Set `spring.security.cookie.secret` (32 characters or more) to the same value on every instance behind a proxy, and to keep cookies valid across restarts; without it, a random key of the process signs them.

Spring's session versions (`HttpSessionRequestCache`, `HttpSessionCsrfTokenRepository`, `HttpSessionOAuth2AuthorizationRequestRepository`) can still be set.

## The session cookie

The cookie is the web starter's (`server.session.cookie.*`): `SameSite=Lax` by default, which single sign-on needs (the provider's redirect is a top-level navigation). Do not make it `Strict` with `oauth2Login()`. See [Sessions in the web starter](../spring-boot-starter-web/sessions.md).

## Several instances

The sessions live in one process. Behind a load balancer, use sticky sessions, or keep logins out of sessions (tokens). A shared session store (Spring Session) is not available yet.

## In Spring (Java)

```java
http.sessionManagement(s -> s
    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
    .maximumSessions(3).maxSessionsPreventsLogin(true));
```

Differences: 10 sessions per user by default (Spring: no limit); ending a session removes it (Spring marks it expired for `ConcurrentSessionFilter`, and has `expiredUrl`); no `invalidSessionUrl`; only `ifRequired` and `stateless`.

## See also

- [CSRF](csrf.md)
- [Form login and HTTP Basic](form-login.md)
- [All properties](properties.md)
