Skip to lesson

Why stateless APIs prefer tokens

ShopLite has a website, an Android app and three server copies. A login kept in one server's memory breaks as soon as the next request reaches another copy. What should carry the proof of sign-in instead?

Stateful (session) vs stateless (token) authentication

Stateless authentication means the server remembers nothing about a signed-in user between requests: every request carries a signed token that already says who the user is and when the token expires.

The first program models two servers in plain Java, one with sessions and one with signed tokens, and sends the same requests to both.

Example 1 · Sessions and tokens on two servers

StatefulVsStatelessDemo.javaJava
import java.nio.charset.StandardCharsets;import java.security.MessageDigest;import java.util.Base64;import java.util.HashMap;import java.util.Map;
import javax.crypto.Mac;import javax.crypto.spec.SecretKeySpec;
/** Stateful: the server remembers who you are in its own memory. */class SessionServer {
    private final String name;    private final Map<String, String> sessions = new HashMap<>();   // session id -> email    private int nextId = 1;
    SessionServer(String name) {        this.name = name;    }
    String login(String email) {        String sessionId = name + "-" + nextId++;        sessions.put(sessionId, email);        return sessionId;    }
    String handle(String sessionId) {        String email = sessions.get(sessionId);        return name + ": " + (email == null ? "who are you? go to /login" : "hello " + email);    }}
/** Stateless: the client carries a signed token; any server with the key can check it. */class TokenServer {
    private final String name;    private final byte[] key;
    TokenServer(String name, byte[] key) {        this.name = name;        this.key = key;    }
    String issue(String email, long expiresAtMinute) throws Exception {        String payload = email + "|" + expiresAtMinute;        return encode(payload.getBytes(StandardCharsets.UTF_8)) + "." + encode(sign(payload));    }
    String handle(String token, long nowMinute) throws Exception {        String[] parts = token.split("\\.");        String payload = new String(Base64.getUrlDecoder().decode(parts[0]), StandardCharsets.UTF_8);        byte[] givenSignature = Base64.getUrlDecoder().decode(parts[1]);        if (!MessageDigest.isEqual(givenSignature, sign(payload))) {            return name + ": bad signature, rejected";        }        String[] fields = payload.split("\\|");        long expiresAt = Long.parseLong(fields[1]);        if (nowMinute >= expiresAt) {            return name + ": token expired, rejected";        }        return name + ": hello " + fields[0] + " (no lookup needed)";    }
    private byte[] sign(String payload) throws Exception {        Mac mac = Mac.getInstance("HmacSHA256");        mac.init(new SecretKeySpec(key, "HmacSHA256"));        return mac.doFinal(payload.getBytes(StandardCharsets.UTF_8));    }
    private static String encode(byte[] bytes) {        return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);    }}
public class StatefulVsStatelessDemo {
    public static void main(String[] args) throws Exception {        System.out.println("-- Sessions: two servers behind a load balancer --");        SessionServer a = new SessionServer("A");        SessionServer b = new SessionServer("B");        String sessionId = a.login("asha.rao@example.com");        System.out.println("cookie: JSESSIONID=" + sessionId);        System.out.println(a.handle(sessionId));        System.out.println(b.handle(sessionId));
        System.out.println("-- Tokens: the same two servers share only a key --");        byte[] sharedKey = "a-32-byte-secret-from-the-config".getBytes(StandardCharsets.UTF_8);        TokenServer tokenA = new TokenServer("A", sharedKey);        TokenServer tokenB = new TokenServer("B", sharedKey);        long issuedAt = 600;                                   // minutes on a pretend clock        String token = tokenA.issue("asha.rao@example.com", issuedAt + 15);        System.out.println(tokenA.handle(token, issuedAt + 1));        System.out.println(tokenB.handle(token, issuedAt + 2));
        String changed = token.replace(token.substring(0, 4), "cmF2");   // someone edits the email        System.out.println(tokenB.handle(changed, issuedAt + 3));        System.out.println(tokenB.handle(token, issuedAt + 15));    }}
Output
-- Sessions: two servers behind a load balancer --
cookie: JSESSIONID=A-1
A: hello asha.rao@example.com
B: who are you? go to /login
-- Tokens: the same two servers share only a key --
A: hello asha.rao@example.com (no lookup needed)
B: hello asha.rao@example.com (no lookup needed)
B: bad signature, rejected
B: token expired, rejected

What this code does

  • SessionServer keeps a map from id to email, so server B cannot recognise an id that A created. TokenServer stores nothing; A and B share only the key, so both accept A's token.
  • Changing four characters of the token breaks the HMAC check: the data can be read but not changed without the key.
  • The last two lines show the price: after Asha logs out, a copied token still works until its expiry at minute 15.

Stateful authentication keeps the signed-in user on the server, in a session, and gives the browser only an id to look it up. A signature (the HMAC idea from the Security basics module) can be checked by any server that has the key, so with tokens any copy of the app can answer any request and nothing has to be shared except the key. With sessions the copy that holds the session must answer, or the sessions must live in a shared store. The token in the demo is a simplified format made for this lesson; the JWT module uses the real standard.

Side by side:

  • Session: small random id in a cookie, the server looks up the user, and it is easy to end at once (delete the session).
  • Token: signed data in a header, the server checks the signature and needs no lookup, but it is hard to end early.

SessionCreationPolicy.STATELESS and what it changes

SessionCreationPolicy tells Spring Security when it may create an HttpSession: ALWAYS, IF_REQUIRED (the default), NEVER, or STATELESS, which never creates one and never reads the SecurityContext from one.

The next two examples compare the default with STATELESS in the Basic lab, then show what goes wrong when STATELESS meets form login.

Example 2 · IF_REQUIRED vs STATELESS in the Basic lab

Runs in: the basic-lab practice project (Spring Boot 4.1)

Java
// basic-lab SecurityConfig: the default policy is IF_REQUIRED; this line changes it.sessionManagement(session -> session    .sessionCreationPolicy(SessionCreationPolicy.STATELESS));
Sample output
1) basic-lab without the sessionManagement lines (default policy IF_REQUIRED); security headers left out:

$ curl -i http://localhost:8080/api/v1/me
HTTP/1.1 401
Set-Cookie: JSESSIONID=E567A3F1143A2EE16A5177C610FDCAC3; Path=/; HttpOnly
WWW-Authenticate: Basic realm="Realm", charset="UTF-8"
Content-Type: application/json

{"timestamp":"2026-10-16T07:22:59.034Z","status":401,"error":"Unauthorized","path":"/api/v1/me"}

$ curl -i -u 'asha.rao@example.com:Mango#2026' http://localhost:8080/api/v1/me
HTTP/1.1 200
Content-Type: application/json

{"email":"asha.rao@example.com","authorities":["ROLE_CUSTOMER","FACTOR_PASSWORD"]}

2) basic-lab as written, with SessionCreationPolicy.STATELESS:

$ curl -i http://localhost:8080/api/v1/me
HTTP/1.1 401
WWW-Authenticate: Basic realm="Realm", charset="UTF-8"
Content-Type: application/json

{"timestamp":"2026-10-16T07:23:32.584Z","status":401,"error":"Unauthorized","path":"/api/v1/me"}

$ curl -i -u 'asha.rao@example.com:Mango#2026' http://localhost:8080/api/v1/me
HTTP/1.1 200
Content-Type: application/json

{"email":"asha.rao@example.com","authorities":["ROLE_CUSTOMER","FACTOR_PASSWORD"]}

What this code does

  • With the default, the guest's 401 creates a session and sets JSESSIONID: Spring saved the request in case a login followed. An API never needs that.
  • With STATELESS, no response sets a cookie. The Basic request works the same, because Basic proves itself on every request anyway.

Example 3 · A mistake: STATELESS with form login

Runs in: the session-lab practice project (Spring Boot 4.1)

Java
// session-lab SecurityConfig with one line too many.formLogin(Customizer.withDefaults()).logout(Customizer.withDefaults()).sessionManagement(session -> session    .sessionCreationPolicy(SessionCreationPolicy.STATELESS));   // WRONG for form login
Sample output
(session-lab with STATELESS added; TOKEN taken from the login page)

$ curl -i -b jar.txt -c jar.txt -d "username=admin@shoplite.example&password=Admin%23Lab2026&_csrf=$TOKEN" http://localhost:8080/login
HTTP/1.1 302
Set-Cookie: JSESSIONID=1F06501B3A4460802F408159CACDD766; Path=/; HttpOnly; SameSite=Lax
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Location: http://localhost:8080/
Content-Length: 0
Date: Fri, 16 Oct 2026 07:26:54 GMT

$ curl -i -b jar.txt -c jar.txt http://localhost:8080/admin
HTTP/1.1 302
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Location: http://localhost:8080/login
Content-Length: 0
Date: Fri, 16 Oct 2026 07:26:54 GMT

What this code does

  • The login POST succeeds (302 to /), but the signed-in user is not saved anywhere, so /admin sends the browser back to /login: an endless login loop.
  • A JSESSIONID still appears, made by the CSRF token store. STATELESS controls Spring's use of the session for the user, not every other part.

With the default, even a pure API makes sessions: a guest's 401 sets a JSESSIONID, because Spring saved the request for a later login. STATELESS switches that off, so every request must prove itself again, which fits Basic and bearer tokens that do exactly that.

STATELESS is a mistake with form login: the login itself succeeds, but the result is never stored, so the very next request is a guest again. CSRF protection, if still on, keeps its token in a session anyway, which is why stateless APIs pair STATELESS with csrf.disable().

Predict the output

What does STATELESS change?

Choose the result for each configuration.

Round 1 of 2

The form login succeeds. What does the next GET /admin return?

http.formLogin(Customizer.withDefaults())
.sessionManagement(s -> s
.sessionCreationPolicy(SessionCreationPolicy.STATELESS));

Tokens for mobile apps, single-page apps and many servers

A bearer token is a signed value that the client sends in Authorization: Bearer <token>. Whoever holds ("bears") it is treated as the signed-in user until it expires.

Tokens fit clients that are not classic web pages: a mobile app keeps the token in the phone's secure storage, and a React site sends the same header to several APIs.

Text
Android app ──┐                        ┌── shoplite-api copy 1 ┐React site  ──┼── Authorization: ──► load ├── shoplite-api copy 2 ├── same signing keyPartner app ──┘   Bearer <token>   balancer└── shoplite-api copy 3 ┘   (from configuration)Any copy checks the signature and the expiry. No sticky sessions, no session store.
  • Scaling: add or restart copies freely; nobody is logged out by a deploy.
  • No cookie means the browser never sends the token by itself, so CSRF is not a risk (the previous lesson).
  • One sign-in style for every client: mobile, web and other services.

The cost of tokens: revocation is hard, so lifetimes must be short

Revocation means making a credential stop working before its natural end. A session is revoked by deleting it; a stateless token cannot be deleted, so it stays valid until its expiry time.

The program below shows a stolen token still working after logout, and the two ways to limit the damage.

Example 4 · Short lifetimes and a deny-list

TokenRevocationDemo.javaJava
import java.util.HashSet;import java.util.Set;
/** What a server can know from a signed token alone: its id, owner and expiry (signature checking left out). */record Token(String id, String email, int expiresAtMinute) {}
class TokenChecker {
    private final Set<String> revokedIds;   // null = pure stateless, nothing stored
    TokenChecker(Set<String> revokedIds) {        this.revokedIds = revokedIds;    }
    String check(Token token, int nowMinute) {        if (nowMinute >= token.expiresAtMinute()) {            return "rejected (expired)";        }        if (revokedIds != null && revokedIds.contains(token.id())) {            return "rejected (revoked)";        }        return "accepted";    }}
public class TokenRevocationDemo {
    static void timeline(String title, Token token, TokenChecker checker) {        System.out.println(title);        int[] minutes = {10, 14, 15, 60 * 24 * 6};        String[] labels = {"minute 10", "minute 14", "minute 15", "day 6    "};        for (int i = 0; i < minutes.length; i++) {            System.out.println("  " + labels[i] + ": thief's request " + checker.check(token, minutes[i]));        }    }
    public static void main(String[] args) {        // Asha signs in at minute 0. A thief copies her token at minute 5; she logs out at minute 6.        Token shortLived = new Token("t-101", "asha.rao@example.com", 15);        Token longLived = new Token("t-102", "asha.rao@example.com", 60 * 24 * 7);
        TokenChecker stateless = new TokenChecker(null);        timeline("15-minute token, logout only forgets it in the app:", shortLived, stateless);        timeline("7-day token, logout only forgets it in the app:", longLived, stateless);
        Set<String> denyList = new HashSet<>();        denyList.add("t-102");                        // logout adds the id to a shared list        timeline("7-day token with a deny-list checked on every request:", longLived, new TokenChecker(denyList));    }}
Output
15-minute token, logout only forgets it in the app:
  minute 10: thief's request accepted
  minute 14: thief's request accepted
  minute 15: thief's request rejected (expired)
  day 6    : thief's request rejected (expired)
7-day token, logout only forgets it in the app:
  minute 10: thief's request accepted
  minute 14: thief's request accepted
  minute 15: thief's request accepted
  day 6    : thief's request accepted
7-day token with a deny-list checked on every request:
  minute 10: thief's request rejected (revoked)
  minute 14: thief's request rejected (revoked)
  minute 15: thief's request rejected (revoked)
  day 6    : thief's request rejected (revoked)

What this code does

  • A thief copies Asha's token at minute 5. With a 15-minute token the stolen copy dies at minute 15; with a 7-day token it works for almost a week after she logs out.
  • The deny-list stops the 7-day token at once, but every request must now check a shared list: state is back, which is why short lifetimes are the usual first answer.

No server keeps a list of tokens, so if a thief copies one, logout in the app only forgets the app's own copy. Token lifetimes must therefore be short, usually minutes (ShopLite uses 15). A short access token limits the damage of a theft; a longer-lived refresh token, stored on the server where it can be revoked, gets new access tokens without asking for the password again. The JWT module builds this.

The other fix is a deny-list: a shared list of revoked token ids checked on every request. It works, but it brings back state and a lookup on every request, the very things tokens avoided.

Comparing Basic, sessions and tokens

The right sign-in style depends on the client and the deployment. This table puts the trade-offs of the whole module side by side.

Text
                Basic               Session cookie          Signed tokenSent each time  password            session id (cookie)     token (header)Server stores   nothing             the session             nothing (or a deny-list)Logout          impossible          delete the session      wait for expiry / refreshCSRF risk       yes, from browsers  yes: keep CSRF on       no, if sent in a headerMany servers    easy                sticky or shared store  easy (share the key)Best for        service calls       server-rendered sites   APIs, mobile apps, SPAs
  • ShopLite API (mobile app, React site, several copies): stateless tokens.
  • ShopLite admin console (a few admins, server-rendered pages): sessions with CSRF on, the module project.
  • Internal service-to-service calls: Basic with a random secret over HTTPS, or tokens.

Next step

Check your understanding

11 quick questions