Sub topic 2
Session Identifiers and Secure Cookies
Assume you know HTTP requests, response headers, cookies, and load balancers. A session identifier is a random value that lets a service find a user's session data. The browser sends it on later requests, usually in a cookie.
Set-Cookie: sid=3q2-7wXk...; Path=/; Max-Age=1800; HttpOnly; Secure; SameSite=LaxHttpOnly prevents browser scripts from reading the cookie. Secure sends it only over HTTPS. SameSite=Lax limits cross-site requests while allowing common top-level navigation. The identifier should be unpredictable and should not contain sensitive data.
A cookie does not make a service stateful by itself. The service is stateful when an instance keeps the session data in local memory or on its local disk. That creates a problem when a later request reaches another instance.
Keeping Sessions in a Shared Store
A shared server-side store, such as Redis, lets every instance load the same session. The cookie contains only an identifier. Set an expiry when creating the record, and refresh it when the session is used if you want sliding expiration.
import json
import secrets
import redis
r = redis.Redis(host="localhost", port=6379, decode_responses=True)
TTL = 1800
def create_session(user_id: str) -> str:
sid = secrets.token_urlsafe(32)
r.set(f"session:{sid}", json.dumps({"user_id": user_id}), ex=TTL)
return sid
def load_session(sid: str):
key = f"session:{sid}"
value = r.get(key)
if value is None:
return None
r.expire(key, TTL)
return json.loads(value)
def destroy_session(sid: str) -> None:
r.delete(f"session:{sid}")Keeping State in Signed Client-Side Tokens
A signed token stores claims, such as a user ID and expiry, in the client cookie. A signature proves that the token was created by a service with the secret key. It does not hide the claims. Use encryption when confidentiality is required.
import hashlib
import hmac
def verify(body: str, mac: str, secret: bytes) -> bool:
expected = hmac.new(secret, body.encode(), hashlib.sha256).hexdigest()
return hmac.compare_digest(mac, expected)Tokens avoid a store lookup and work well across instances, but revocation is difficult. A stolen token remains valid until it expires unless you maintain a denylist or change the signing key. Rotate tokens after login or privilege changes, and use short lifetimes for sensitive sessions.
Exercise
Which approach allows immediate deletion of one user's session with a simple record operation?
Show answer
A shared server-side session store. Delete the record, then reject requests whose identifier no longer resolves.