Latticework

Command Palette

Search for a command to run...

Authentication

Sessions vs Tokens

16 min

Explanation

After a user logs in, the server needs a way to recognize them on every SUBSequent request without asking for a password again. Two dominant approaches:

Session-based: the server generates a random session ID, stores it (with the user's info) in a server-side store (memory, Redis, a database), and sends the ID to the client as a cookie. Every request, the server looks up the session ID to find out who's asking.

def validate_session(session_store, session_id):
    return session_store.get(session_id)   # None if not found/expired
Try it

Every validate_session call requires a lookup against server-side state -- that lookup is the defining cost (and the defining SIMPLICITY -- instant revocation, just delete the entry) of the session approach.

Loading editor…
Explanation

Token-based (e.g. JWT): the server issues a signed token containing the user's info directly, with an EXPIRATION time baked in. The server verifies the signature (fast, no database lookup) instead of looking anything up:

def is_token_expired(issued_at, ttl_seconds, current_time):
    return current_time > issued_at + ttl_seconds

Tokens scale better (no shared session store needed across servers) but can't be instantly revoked — once issued, a token stays valid until it expires, even if you'd want to cut it off sooner (a compromised account, for example). Sessions trade that scalability for instant control: delete the server-side entry, and the session is dead immediately.

Exercise

Write `is_token_expired(issued_at, ttl_seconds, current_time)`, returning True if `current_time` is strictly after `issued_at + ttl_seconds`.

Exercise

Write `validate_session(session_store, session_id)`: look up `session_id` in the `session_store` dict, returning the associated user info, or None if it isn't found.

Quiz

What's a key architectural difference between session-based auth and token-based (e.g. JWT) auth?

Checkpoint

You understand the session-vs-token tradeoff (server-side lookup + instant revocation vs. self-contained + no revocation until expiry), and can implement expiration checking and session lookup.