Sessions vs Tokens

HTTP Is Stateless

HTTP does not remember you between requests. After login, the server must recognise you on the next request. There are two main approaches:

Session (stateful)Token (stateless, e.g. JWT)
After login the server...stores user data in a server-side sessionsigns a token holding the user data
Client sendsCookie: JSESSIONID=...Authorization: Bearer eyJ...
Server checkslooks up the session id in memory/Redisverifies the signature, no lookup
Logouteasy: delete the sessionharder: token valid until it expires
Best forserver-rendered web apps, same-site SPAsmobile apps, public APIs, microservices
Spring SecurityformLogin() (default)JWT filter or oauth2ResourceServer()

How a Session Works

Example

A session store is just a map from a random id to the user. The id travels in a cookie:

import java.util.*;

public class Main {
    static final Map<String, String> SESSIONS = new HashMap<>();
    static int counter = 1000;

    static String login(String user) {
        String sessionId = "S" + (++counter);       // real servers use long random ids
        SESSIONS.put(sessionId, user);
        return sessionId;
    }

    static String request(String path, String cookie) {
        String user = cookie == null ? null : SESSIONS.get(cookie);
        return "GET " + path + " Cookie=" + cookie + " -> " + (user == null ? "401" : "200 hello " + user);
    }

    public static void main(String[] args) {
        String id = login("asha");
        System.out.println("Set-Cookie: JSESSIONID=" + id);
        System.out.println(request("/api/cart", id));
        System.out.println(request("/api/cart", null));
        System.out.println(request("/api/cart", "S9999"));   // guessed id
        SESSIONS.remove(id);                                 // logout
        System.out.println(request("/api/cart", id));
    }
}

Output

Set-Cookie: JSESSIONID=S1001
GET /api/cart Cookie=S1001 -> 200 hello asha
GET /api/cart Cookie=null -> 401
GET /api/cart Cookie=S9999 -> 401
GET /api/cart Cookie=S1001 -> 401

Which Does This Course Use?

The basic level uses sessions (form login) for the browser and HTTP Basic for API clients, because they need no extra code. The medium level replaces HTTP Basic with JWT tokens for the React frontend and mobile app.

Note: Session cookies should be HttpOnly (JavaScript cannot read them), Secure (HTTPS only) and SameSite=Lax or Strict. Spring Boot sets HttpOnly by default; set the others with server.servlet.session.cookie.secure=true and server.servlet.session.cookie.same-site=lax.