Sub topic 8
Expiry, Rotation and Revocation
This chapter covers how a session ends, how its identifier changes during its life, and how you cut it off early. It assumes you know HTTP cookies and headers, and that you have seen the two main designs from earlier chapters: a shared server-side store (such as Redis) and signed client-side tokens. The three operations work very differently in each design. That difference often decides which design fits a system.
Three lifecycle operations
A session has a start, a middle and an end. Three operations control that life.
- Expiry ends a session automatically after some 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.
A server-side store holds the state, so it can do all three directly. A signed token carries its own state, so the server cannot change or delete it. Expiry is easy for tokens. Revocation is the hard part.
Expiry
Expiry limits how long a stolen or forgotten session stays useful. Two clocks are common, and they answer different questions.
| Clock | Meaning | Typical value |
|---|---|---|
| Idle timeout | Time since the last request | 15 to 30 minutes |
| Absolute timeout | Time since the session was created | 8 hours to 30 days |
Use both. An idle timeout alone lets an active session live forever. An absolute timeout alone logs out a user in the middle of work.
Expiry in a server-side store
In the Redis example from earlier, the key has a time to live (TTL). Redis deletes the key when the TTL runs out, so idle sessions disappear with no cleanup job. The load_session function resets the TTL on each read. That is a sliding expiry, and it implements the idle timeout.
Sliding expiry alone gives no absolute limit, because a session that is used every few minutes never expires. To add one, store the creation time inside the session and check it on each load.
import json
import secrets
import time
import redis
r = redis.Redis(host="localhost", port=6379, decode_responses=True)
IDLE_TTL_SECONDS = 1800 # 30 minutes of inactivity
ABSOLUTE_TTL_SECONDS = 8 * 3600 # 8 hours in total
def create_session(user_id: str) -> str:
session_id = secrets.token_urlsafe(32)
data = {"user_id": user_id, "created_at": time.time()}
r.set(f"session:{session_id}", json.dumps(data), ex=IDLE_TTL_SECONDS)
return session_id
def load_session(session_id: str):
key = f"session:{session_id}"
raw = r.get(key)
if raw is None:
return None
data = json.loads(raw)
age = time.time() - data["created_at"]
if age > ABSOLUTE_TTL_SECONDS:
r.delete(key)
return None
# Never extend the key past the absolute limit.
remaining = int(ABSOLUTE_TTL_SECONDS - age)
r.expire(key, min(IDLE_TTL_SECONDS, max(remaining, 1)))
return dataThe min(...) call keeps the sliding TTL from running past the absolute deadline, so Redis also removes the key on time.
Expiry in a signed token
A signed token has no TTL on a server. The expiry is a claim inside the payload, such as exp, and the signature stops the client from changing it. The verify function from the previous chapter rejects a token when exp is in the past. Each instance does this check on its own, with no shared lookup.
The server cannot extend a token's life, because it cannot edit the payload without re-signing it. To get a sliding expiry, the server issues a fresh token with a later exp in the response. This is a form of rotation, covered next.
Clock differences between instances matter here. If one instance's clock is a minute ahead, it may reject a token that another instance just issued. Run time synchronization (NTP) on every host. Some systems also allow a small leeway, such as 30 seconds, when they compare exp to the current time.
Rotation
Rotation means the client receives a new identifier or token and the old one stops working. There are three common reasons to do it.
- Privilege change. Issue a new identifier when a user logs in or gains higher privileges. This blocks session fixation, where an attacker plants a known session ID in a victim's browser before login and then uses it after the victim authenticates.
- Periodic renewal. Replace the identifier every so often so a leaked one has a short useful life.
- Short-lived access. Keep a token's lifetime short and renew it, so you only have to worry about a small window.
Rotating a server-side session
Create the new session, copy the data across, then delete the old key. Do it in one atomic step so a crash cannot leave the user with two live identifiers or none.
def rotate_session(old_id: str):
old_key = f"session:{old_id}"
new_id = secrets.token_urlsafe(32)
new_key = f"session:{new_id}"
pipe = r.pipeline(transaction=True)
pipe.get(old_key)
raw, = pipe.execute()
if raw is None:
return None
pipe = r.pipeline(transaction=True)
pipe.set(new_key, raw, ex=IDLE_TTL_SECONDS)
pipe.delete(old_key)
pipe.execute()
return new_idThe route that calls rotate_session must then send the new ID in a fresh Set-Cookie header. Always rotate at login, before you store the authenticated user in the session.
A concurrency problem appears when a page fires several requests at once. If the first one rotates the ID, the others still carry the old ID and fail. Two fixes are common. You can rotate only on specific events, such as login. Or you can keep the old key alive for a short grace period, around 10 to 30 seconds, instead of deleting it right away.
Rotating tokens with a refresh token
For signed tokens, the standard pattern uses two tokens.
- The access token is short-lived, often 5 to 15 minutes. Instances verify it by signature alone.
- The refresh token is long-lived. The client sends it to a token endpoint to get a new access token.
The refresh token is the part you track on the server. Store it, or a hash of it, in a database. Each time the client uses a refresh token, issue a new one and mark the old one as used. If a used refresh token appears a second time, someone has copied it. At that point revoke the whole chain of tokens for that login.
This design keeps most requests stateless, since access tokens need no lookup. Only the occasional refresh touches shared storage.
Revocation
Revocation is where the two designs differ the most.
Revocation with a server-side store
Deleting the key revokes the session. The next request finds nothing and the user is logged out. This takes effect on every instance at once, because they all read the same store.
You can also revoke many sessions at a time. Keep a set of session IDs per user, so "log out everywhere" or a password change can delete them all.
def create_session_indexed(user_id: str) -> str:
session_id = create_session(user_id)
r.sadd(f"user_sessions:{user_id}", session_id)
r.expire(f"user_sessions:{user_id}", ABSOLUTE_TTL_SECONDS)
return session_id
def revoke_all_sessions(user_id: str) -> int:
index_key = f"user_sessions:{user_id}"
session_ids = r.smembers(index_key)
keys = [f"session:{sid}" for sid in session_ids]
deleted = r.delete(*keys) if keys else 0
r.delete(index_key)
return deletedThe index can hold IDs of sessions that already expired. That is harmless, because deleting a missing key does nothing, and the index expires too.
Revocation with a signed token
A signed token stays valid until exp, no matter what the server does, because verification needs no lookup. Four approaches exist, each with a cost.
| Approach | How it works | Cost |
|---|---|---|
| Short lifetime | Access tokens live for minutes, and revoking the refresh token stops renewal | Access stays valid until `exp`, a delay of up to the lifetime |
| Denylist | Store the ID (`jti`) of each revoked token until it would have expired | Every request needs a lookup, which brings back a shared store |
| Per-user version | Put a `token_version` claim in the token and compare it to a stored value | A lookup on every request, but only one small value per user |
| Key rotation | Change the signing secret to invalidate every token | Logs out all users, so use it only after a key leak |
A denylist is small, because it only holds tokens that were revoked and are not yet expired. But it needs the shared store that tokens were meant to avoid. If you check it on every request, you have a hybrid: signed tokens plus a server-side lookup. That hybrid is often the right choice when immediate logout is a requirement.
def is_revoked(payload: dict) -> bool:
return r.exists(f"revoked:{payload['jti']}") == 1
def revoke_token(payload: dict) -> None:
ttl = int(payload["exp"] - time.time())
if ttl > 0:
r.set(f"revoked:{payload['jti']}", "1", ex=ttl)The denylist entry gets a TTL equal to the token's remaining life. After the token expires, it no longer needs listing, so the denylist cleans itself.
Cookie lifetime must match
The cookie attributes should agree with the server-side limits. Max-Age on the cookie only asks the browser to drop the cookie. It does not stop a copied value from working. The server decides whether the session is valid.
- Set
Max-Ageclose to the idle timeout, and re-send the cookie when you slide the expiry. - A cookie with no
Max-AgeorExpiresis a session cookie, which most browsers delete when they close. Do not treat that as a security control. Browsers can restore sessions. - At logout, delete the server-side session first, then send
Set-CookiewithMax-Age=0to clear the cookie.
Choosing lifecycle settings
A few rules cover most systems.
- Rotate the session ID at login and at any privilege change.
- Use an idle timeout and an absolute timeout together.
- Make logout and password change revoke every session for that user.
- For tokens, keep access tokens short, rotate refresh tokens, and detect reuse.
- If you need logout to take effect at once with tokens, accept a lookup per request and use a denylist or a version check.
- Test the full life of a session: create, use, idle out, hit the absolute limit, rotate, revoke.
Exercises
Exercise
A team uses signed tokens with a 24-hour exp and no server-side tracking. A user reports a stolen laptop and asks to be logged out everywhere. Why can the team not do this, and what is the smallest change that fixes it?
Show answer
Verification uses only the signature and exp, so no instance consults any server data, and nothing the server stores can invalidate a token already issued. The smallest fix is to shorten the access token lifetime to minutes, add a refresh token the server tracks, and revoke the refresh token on request. If the stolen token must stop working at once, add a denylist or a per-user version check on each request.
Exercise
Your Redis session code resets the TTL to 30 minutes on every request and has no other limit. A user stays active for 5 days. What happens, and how do you change the code?
Show answer
The session stays valid for the whole 5 days, because each request pushes the idle deadline forward. To fix it, store created_at in the session data, reject and delete the session when its age passes an absolute limit such as 8 hours, and cap each TTL reset at the time left before that limit.