Sub topic 7
Keeping State in Signed Client-Side Tokens
This chapter assumes you know HTTP headers and cookies, have built a web service or API in some language, and know what a load balancer does. It also assumes you have seen the shared server-side session store from earlier in this tutorial. Here you will move the session data out of the servers and into the client.
The idea
With a shared session store, the browser holds an opaque identifier and the server looks up the data on every request. A client-side token reverses this. The server puts the session data in the token, signs it, and gives it to the client. On each request the client sends the token back, and the server checks the signature instead of querying a store.
Any instance that holds the signing secret can verify any token. No instance keeps session data, so there is no lookup, no store to run, and no store outage to survive. The costs are weaker revocation, larger requests, and data that the client can read.
What a signed token contains
A typical token has two parts joined by a dot:
- Body. The session data, usually JSON, encoded with URL-safe Base64. It holds the user ID, a few claims, and an expiry time.
- Signature. A keyed hash of the body. This chapter uses HMAC-SHA256. An HMAC (hash-based message authentication code) is computed from the body and a secret key. Without the key, nobody can produce a valid signature for a changed body.
The signature gives you integrity and authenticity. If someone edits the body, the signature no longer matches. Only a party holding the key can create a token that passes.
Signing and verifying in Python
This is a complete script. It signs a payload, verifies it, and shows that tampering is rejected.
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
if __name__ == "__main__":
secret = b"replace-with-32-random-bytes-from-a-secret-manager"
token = sign({"user_id": "42", "role": "user", "exp": time.time() + 900}, secret)
print("valid: ", verify(token, secret))
# An attacker rewrites the body but cannot recompute the signature.
_, old_mac = token.rsplit(".", 1)
forged_body = _b64(json.dumps({"user_id": "42", "role": "admin", "exp": time.time() + 900}).encode())
print("tampered:", verify(f"{forged_body}.{old_mac}", secret))
# A token signed with a different key is also rejected.
print("wrong key:", verify(token, b"another-secret"))The first call prints the payload. The other two print None.
Four details in verify matter:
- Constant-time comparison.
hmac.compare_digesttakes the same time whether the first byte or the last byte differs. A plain==can leak timing information that helps an attacker guess a valid signature byte by byte. - Signature before parsing. The function decodes the body only after the signature passes. Never parse or act on data you have not authenticated.
- Expiry inside the signed body. The
expclaim is covered by the signature, so the client cannot extend it. - Failure returns
None. Callers treat any failure the same way, as an unauthenticated request. Don't tell the client which check failed.
How a request flows
After login, any instance can handle any request, and the instances never talk to each other.
Where the client keeps the token
The server decides how the token travels. There are two common choices.
| Storage | Sent how | Main risk | Defense |
|---|---|---|---|
| Cookie with `HttpOnly`, `Secure`, `SameSite` | Automatically by the browser | CSRF (cross-site request forgery): another site makes the browser send the cookie | `SameSite=Lax` or `Strict`, plus CSRF tokens for state-changing requests |
| `localStorage`, sent in an `Authorization` header | By your JavaScript | XSS (cross-site scripting): injected script can read the token | Strict content security policy, careful output escaping |
For browser applications, an HttpOnly cookie is usually the safer default, because scripts cannot read it. This is the cookie from the earlier chapter, with the token as its value:
Set-Cookie: sid=eyJ1c2VyX2lkIjoiNDIifQ.9f2c...; Path=/; Max-Age=900; HttpOnly; Secure; SameSite=LaxHeader-based tokens suit mobile apps and service-to-service calls, where there is no ambient cookie behaviour to exploit.
Size limits
Browsers typically accept about 4 KB per cookie, and many servers and proxies cap total header size at 8 KB or less. The token travels on every request, including requests for images and scripts if the cookie's path and domain cover them. Keep the body small:
- Store identifiers and a few flags, not whole profiles or shopping carts.
- Look up larger or fast-changing data by user ID in a database.
- Don't embed a list of permissions that can grow without bound.
The revocation problem
This is the main weakness of client-side tokens. A valid token is valid until exp, because no server holds a record that could be deleted. If a user logs out, changes their password, or is banned, a copy of the old token still passes verification.
You have four options, and each gives back part of the benefit of statelessness:
- Short lifetimes. Issue tokens that last 5 to 15 minutes. A stolen token is useful only briefly. The cost is that users must obtain new tokens often.
- Refresh tokens. Pair the short-lived access token with a long-lived refresh token. The refresh token is an opaque ID kept in a server-side store, so you can revoke it. Revocation then takes effect within one access-token lifetime. The refresh path is stateful, but it sees far less traffic than every request does.
- Denylist. Give each token an ID (
jti) and keep revoked IDs in a fast store such as Redis until their natural expiry. Every request now checks the store, so you are close to running a session store again. The list only needs to hold entries that have not yet expired. - Version counter. Keep a
session_versionnumber per user and include it in the token. Bump the number on logout-everywhere or password change, and reject tokens with an older version. This too needs a lookup per request, though a small one that is easy to cache.
Choose the cheapest option that meets your revocation requirement. If you must be able to cut off a session immediately, a shared store is simpler than patching a token scheme.
Rotating the signing key
The secret is the single point of trust. Anyone who obtains it can mint a token for any user, so you need a way to replace it without logging everyone out. Accept several keys when verifying, and sign with only the newest:
import hashlib
import hmac
def verify_with_keys(token: str, keys: list[bytes]):
"""Return the payload if any key in `keys` validates the token."""
for key in keys:
payload = verify(token, key)
if payload is not None:
return payload
return None
# Rotation: deploy [new, old], then sign with new.
# After the longest token lifetime has passed, drop old.This code reuses verify from the earlier script. The rotation steps are:
- Add the new key to the verify list on every instance, still signing with the old key.
- Switch signing to the new key.
- Wait longer than the maximum token lifetime.
- Remove the old key.
Deploying the new key to every instance before you switch signing matters. If you skip step 1, an instance still running the old configuration will reject tokens signed with the new key.
If a key leaks, skip the grace period and remove the old key immediately. All sessions end, which is the correct outcome.
Common errors
- Trusting the algorithm named in the token. JWT (JSON Web Token) headers declare the signing algorithm, and early libraries accepted
alg: noneor let an attacker switch from an asymmetric algorithm to HMAC. Fix the accepted algorithm in your server code, and never read it from the token. - No expiry. A token without
explives forever. Reject any token that lacks the claim. - Weak or shared secrets. A short or guessable key can be brute-forced offline, since an attacker can test guesses against a captured token without touching your server. Use at least 32 random bytes from a secret manager, and use different keys per environment.
- Treating the body as private. See the warning above.
- Authorizing from stale claims. A token that says
"role": "admin"keeps saying so until it expires, even after you remove the role. For sensitive actions, re-check the current role in the database. - Clock differences. Instances with drifting clocks disagree about expiry. Keep clocks synchronized with NTP, and allow a small leeway, such as 30 seconds, if you verify tokens across services.
- Storing the token in
localStoragefor convenience. Any XSS bug then exposes every session. Prefer anHttpOnlycookie.
When this approach fits
Signed tokens work well when:
- requests are verified by many services, and you don't want each one to reach a session store;
- sessions are short or revocation within minutes is acceptable;
- session data is small and changes rarely.
They fit poorly when you need instant logout, large per-session data, or server-side changes to the session, such as updating a cart on every request. A shared store handles those cases better, at the cost of running it and planning for its failure.
Exercise
A user clicks "log out of all devices" on your site. Your service uses 15-minute signed tokens with no server-side state. Name two ways to make old tokens stop working sooner than 15 minutes, and say what each one costs.
Show answer
Option 1: a per-user session version stored in a database or cache. Put the version in the token, bump it on "log out of all devices", and reject tokens whose version is older. Cost: a lookup on every request (cacheable), so the service is no longer fully stateless. Option 2: a denylist of token IDs (jti) kept until each token's expiry. Cost: a store check on every request, and you need the token IDs to revoke. A third answer is also acceptable: shorter token lifetimes with a revocable refresh token, which costs more frequent refresh calls and a small stateful refresh endpoint.
Exercise
In the verify function, why is the signature compared with hmac.compare_digest instead of ==, and why is json.loads called only after the comparison?
Show answer
== on strings can return as soon as it finds a differing character, so response time reveals how many leading characters were correct, which an attacker can exploit to forge a signature gradually. compare_digest takes constant time. The body is parsed only after the signature passes because until then it is untrusted input chosen by the client, and you should not process data you have not authenticated.