Sub topic 7
Keeping state in signed client-side tokens
This chapter assumes you know HTTP headers and cookies, have built a web API, and understand what a load balancer does. It also assumes you have seen the shared session store approach from the previous chapter.
The idea
A shared store keeps session data on the server side and gives the client only an ID. A signed token reverses this. The server puts the session data into the token, signs it, and gives it to the client. The client sends the token back on each request. Any instance that holds the signing secret can check the signature and read the data. No lookup is needed.
Because the instances share only a secret, and no data, they stay stateless. The load balancer can send any request to any instance.
Signing a token
The token has two parts: an encoded body and a message authentication code (MAC). A MAC is a short value computed from the body and a secret key. Without the key, nobody can produce a valid MAC for a changed body.
import base64
import hashlib
import hmac
import json
import time
def _b64(data: bytes) -> str:
return base64.urlsafe_b64encode(data).decode().rstrip("=")
def sign(payload: dict, secret: bytes) -> str:
body = _b64(json.dumps(payload, separators=(",", ":")).encode())
mac = hmac.new(secret, body.encode(), hashlib.sha256).hexdigest()
return f"{body}.{mac}"
def verify(token: str, secret: bytes):
try:
body, mac = token.rsplit(".", 1)
except ValueError:
return None
expected = hmac.new(secret, body.encode(), hashlib.sha256).hexdigest()
if not hmac.compare_digest(mac, expected):
return None
padded = body + "=" * (-len(body) % 4)
payload = json.loads(base64.urlsafe_b64decode(padded))
if payload.get("exp", 0) < time.time():
return None
return payload
# token = sign({"user_id": "42", "exp": time.time() + 900}, secret)sign encodes the payload as compact JSON, then computes an HMAC-SHA256 over the encoded body. verify splits the token, recomputes the MAC, and compares it in constant time with hmac.compare_digest. A normal == comparison can leak timing information. Only after the signature passes does verify decode the body and check the exp (expiry) claim. It returns None for any failure, so callers handle one failure path.
What signing does and does not do
Signing gives integrity. If a client edits the body, for example by changing user_id to 1, the MAC no longer matches and the token is rejected.
Signing does not give confidentiality. The body is only base64 encoded, so anyone holding the token can read it. Do not put passwords, personal data, or internal details in the payload. If you need secrecy, use authenticated encryption, or keep the data on the server.
Common errors
- Trusting the payload before verifying. Always check the signature first, then read any claim.
- No expiry. A token without
expis valid forever. Always set a short lifetime and check it. - Weak or hard-coded secrets. Use a long random key from the environment or a secrets manager, never from source code.
- Skipping constant-time comparison. Use
hmac.compare_digest. - Large payloads. The token travels with every request. Cookies are limited to about 4 KB, and a large token adds bandwidth to every call.
- Stale data. The payload is a copy made at login. If a user's role changes, existing tokens still carry the old role until they expire.
Trade-offs
| Property | Signed token | Shared store |
|---|---|---|
| Lookup per request | None | One store read |
| Extra infrastructure | None | Store cluster |
| Instant revocation | Hard | Delete the key |
| Data visible to client | Yes | No |
| Size per request | Grows with data | Small ID |
| Secret handling | All instances share the key | Store credentials |
The main weakness is revocation. The server holds no record of issued tokens, so it cannot simply delete one. A stolen token stays valid until exp. Common mitigations are short lifetimes (often 5 to 15 minutes) combined with a longer-lived refresh mechanism, or a small deny list of revoked token IDs. A deny list brings back a shared lookup, though a much smaller one than a full session store.
Secret rotation is the second cost. Changing the key invalidates every token signed with the old one. To rotate smoothly, include a key ID in the token and let instances verify against both the old and the new key during a transition period.
Delivering the token
A browser client can receive the token in a cookie. Use attributes that limit exposure:
Set-Cookie: sid=3q2-7wXk...; Path=/; Max-Age=1800; HttpOnly; Secure; SameSite=LaxHttpOnly blocks scripts from reading the cookie, Secure limits it to HTTPS, and SameSite=Lax restricts cross-site sending. Non-browser clients usually send the token in an Authorization header instead.
When to choose it
Signed tokens fit when you want no per-request lookup, when many services must verify the same identity, or when you cannot run a session store. They fit poorly when you need immediate logout, per-session administration, or large amounts of session data.
Exercise
A user's account is compromised. Your system uses signed tokens that expire after 15 minutes, with no deny list. The attacker holds a valid token. What is the longest the attacker can keep using it, and what is one way to shorten that window?
Show answer
The attacker can use the token until it expires, so up to 15 minutes. You can shorten the window by using a shorter lifetime, or by adding a small deny list of revoked token IDs that each instance checks. The deny list adds a shared lookup but allows immediate revocation.
Exercise
Why does verify check the MAC before it decodes the body and reads exp?
Show answer
The body is untrusted until the signature matches. Parsing or acting on it first could let a tampered or malformed payload influence the server. Verifying first means only data the server itself signed is ever read.