Sub topic 8
Expiry, rotation and revocation
This chapter assumes you know how HTTP cookies work and have seen the two storage approaches from earlier chapters: a shared server-side store (for example Redis) and signed client-side tokens. Here we look at how a session ends, how its identifier changes, and how you cut it off early.
Three lifecycle operations
- Expiry ends a session after a set time.
- Rotation replaces the session identifier or token with a new one while the user stays logged in.
- Revocation ends a session on purpose before it would expire, for example at logout or after a password change.
Each approach handles these differently. The main difference is whether the server can forget a session by itself.
Expiry
There are two kinds of expiry, and most systems use both.
- Idle (sliding) timeout: the session ends after a period with no requests. Each use pushes the deadline forward.
- Absolute timeout: the session ends a fixed time after creation, however active the user is.
In a shared store, the store enforces expiry. The key's TTL (time to live) removes the session without any cleanup code. The load_session function from the store example does this:
def load_session(session_id: str):
key = f"session:{session_id}"
data = r.get(key)
if data is None:
return None
r.expire(key, SESSION_TTL_SECONDS) # sliding expiry
return json.loads(data)r.expire resets the TTL on every read, so this is an idle timeout only. A user who makes a request every few minutes would stay logged in forever. To add an absolute limit, store a created_at value in the session data and reject the session when it is too old.
A signed token has no store to expire it, so the token carries its own deadline. The verify function checks the exp field after it checks the signature:
if payload.get("exp", 0) < time.time():
return NoneA token cannot extend itself. To get a sliding timeout, the server must issue a new token with a later exp, which is rotation.
The cookie lifetime (Max-Age) is separate from server-side expiry. The browser deletes the cookie when Max-Age passes, but a client can ignore that. The server must always check expiry itself and never rely on the cookie alone.
Rotation
Rotate the identifier at these moments:
- At login. If an attacker planted a known session ID in the victim's browser before login (session fixation), the old ID must stop working. Always issue a fresh ID when a user authenticates.
- At privilege changes, such as re-entering a password to reach a sensitive page.
- Periodically, to limit how long a stolen ID is useful.
With a shared store, rotation means creating a new key, copying the data, and deleting the old key:
def rotate_session(old_id: str):
data = load_session(old_id)
if data is None:
return None
new_id = secrets.token_urlsafe(32)
r.set(f"session:{new_id}", json.dumps(data), ex=SESSION_TTL_SECONDS)
r.delete(f"session:{old_id}")
return new_idThe function returns the new ID, and the response must set it in a new Set-Cookie header. If two requests arrive at once with the old ID, one may fail after the other rotates it. Some systems keep the old ID valid for a few seconds to absorb this.
With signed tokens, rotation means signing a new payload with a new exp. Short-lived access tokens (about 15 minutes) paired with a longer-lived refresh credential are common. The refresh credential is usually stored on the server so it can be revoked.
Revocation
Revocation is where the two approaches differ most.
With a shared store, destroy_session deletes the key. The next request on any instance finds nothing and fails. Revocation is immediate. This also lets you "log out everywhere": keep a set of session IDs per user and delete them all.
With a signed token, any instance can verify the token using only the secret, so no instance knows that you want it revoked. Your options are:
- Short expiry. Accept that a stolen token works until
exp. Keep the window small. - Deny list. Store revoked token IDs (a
jticlaim) until theirexppasses, and check the list on each request. This adds a lookup per request, which brings back the shared store you were trying to avoid, though a small one. - Per-user version number. Put a
versionin the token and keep the current version per user. Increment it on password change or "log out everywhere". Tokens with an older version are rejected. This also needs a lookup.
Comparison
| Operation | Shared store | Signed token |
|---|---|---|
| Idle expiry | TTL reset on each read | Reissue token with later `exp` |
| Absolute expiry | Check `created_at` | `exp` claim |
| Rotation | New key, delete old | Sign a new payload |
| Single revocation | Delete the key | Needs a deny list |
| Revoke all for a user | Delete the user's keys | Needs a version number or a new secret |
Common errors
- Trusting
Max-Ageon the cookie instead of checking expiry on the server. - Keeping the same session ID across login.
- Setting only a sliding timeout, so sessions never end.
- Using long-lived signed tokens with no way to revoke them.
- Forgetting to expire entries in a deny list, so it grows without bound.
Exercise
A user changes their password. Your app uses signed tokens that expire after 24 hours, with no server-side lookups. Why is this a problem, and what is the smallest change that fixes it?
Show answer
Tokens issued before the change stay valid until they expire, so a thief who holds an old token keeps access for up to 24 hours. The smallest fix is to shorten the lifetime and add a per-user version number. Store the version with the user record, put it in each token, increment it on password change, and reject tokens whose version does not match. This adds one lookup per request, which is the cost of immediate revocation.
Exercise
Your shared-store load_session resets the TTL on every read. What kind of timeout does this give, and what must you add so a session cannot last forever?
Show answer
It gives an idle (sliding) timeout. Add an absolute timeout by saving a created_at time in the session data and rejecting the session once it is older than the allowed maximum, even if it was used recently.