The problem with a long-lived token
A signed token is self-contained by design: the server verifies the signature, reads the claims, and answers. No lookup, no shared state, no database on the hot path. That property is exactly why it scales, and exactly why it is dangerous.
A stateless token cannot be revoked. If it says you are an administrator and it is valid for seven days, then you are an administrator for seven days — after you are fired, after the laptop is stolen, after someone copies it out of local storage. The only thing that ends it is the expiry baked into it when it was signed.
Teams discover this and reach for a revocation list, which is a database lookup on every request, and now the token is not stateless and you have the costs of both designs. The better answer is to make the stateless part short-lived enough that revocation does not need to reach it.
The shape of the answer
Two tokens, with different jobs.
| Access token | Refresh token | |
|---|---|---|
| Contains | Signed claims: who, what role, what permissions | Nothing. 256 random bits. |
| Lifetime | 15 minutes | 30 days, or 1 day without "remember me" |
| Verified by | A signature check. No database. | A database lookup. Every time. |
| Revocable | No — but it expires in 15 minutes | Yes, immediately |
| Sent on | Every request | Only the refresh endpoint |
The access token keeps the property you wanted: no state on the hot path. The refresh token carries the revocability, and it is presented rarely enough that a database lookup costs nothing. Fifteen minutes is the window of exposure, and fifteen minutes is short enough that "revoke" means "within fifteen minutes" rather than "within a week".
Rotation, and why it has to rotate
A refresh token that stays the same for thirty days is the long-lived credential you were trying to avoid, moved one endpoint to the left. So every use of it issues a new one and invalidates the old.
One detail decides whether this is secure or theatre: the replacement must inherit the original's expiry, not get a fresh thirty days. Otherwise an attacker who has the token refreshes it every twenty-nine days and holds the session forever. The chain must have an end, fixed at the moment of login.
public async Task<Session> RotateAsync(string presented)
{
var hash = Sha256(presented);
var stored = await _db.RefreshTokens
.FirstOrDefaultAsync(t => t.Hash == hash);
if (stored is null) return Session.Denied;
if (stored.ExpiresOn < _clock.UtcNow) return Session.Denied;
if (stored.RotatedOn is not null)
{
// Already used once. Somebody has a copy.
await RevokeFamilyAsync(stored.FamilyId);
return Session.Denied;
}
stored.RotatedOn = _clock.UtcNow;
var next = new RefreshToken {
FamilyId = stored.FamilyId, // same chain
ExpiresOn = stored.ExpiresOn, // inherited, never extended
IsPersistent = stored.IsPersistent,
Hash = Sha256(plaintext = NewSecret())
};
_db.RefreshTokens.Add(next);
await _db.SaveChangesAsync();
return Session.Issue(plaintext, NewAccessToken(stored.UserId));
}
Detecting a stolen token
Rotation gives you something better than protection: it gives you detection.
Every token issued from one login shares a FamilyId. In normal use the chain is strictly
linear — each token is used exactly once and replaced. So if a token that has already been
rotated is presented again, there are two copies of it in the world, and only one of them
can be the legitimate client.
You cannot tell which. So you end the whole family: every token in the chain is revoked, both parties are logged out, and the real user signs in again and gets a new chain. Mildly annoying for them. Fatal for the attacker.
Where the tokens live
Three decisions, and the third one is the one that breaks in production.
Store the hash, never the token
The refresh token is a bearer credential: whoever holds it is you. Storing it in plaintext means a
read-only SQL injection or a leaked backup hands over every live session. Store
SHA-256(token) and compare hashes. It is one line, and it turns a catastrophe into a
non-event.
Unlike a password, this does not need a slow hash. The token is 256 random bits, so there is no dictionary to attack and nothing to brute force.
Cookies, not local storage
If JavaScript can read the token, then so can any script that gets onto your page — a compromised
dependency, an injected analytics tag, a stored XSS. httpOnly cookies are not readable
by JavaScript at all, which removes the entire class.
Response.Cookies.Append("refresh_token", token, new CookieOptions
{
HttpOnly = true,
Secure = true,
SameSite = SameSiteMode.Lax,
Path = $"{pathBase}/user", // see below
Expires = rememberMe ? expiresOn : null
});
The cost is that you now have to think about CSRF, because cookies are sent automatically.
SameSite handles the common cases; a token header or a double-submit cookie handles the
rest. That is a real cost, and it is still a better trade than making the credential readable by every
script on the page.
The path has to include the path base
Scoping the refresh cookie to the refresh endpoint is good practice: it means the long-lived credential is not attached to every image request. It is also where I have watched this design fail.
If the application is hosted behind a path base — UsePathBase("/api") — then the server
sees /user/refresh but the browser sees /api/user/refresh.
A cookie scoped to Path=/user is never sent, the refresh endpoint receives nothing, and
every user is silently logged out fifteen minutes after signing in.
Taking permissions away, instantly
Here is the problem the two-token design leaves open. An administrator removes someone's permission to approve payments. The claim is in a signed token that is valid for another fourteen minutes. The server has no idea anything changed.
Fourteen minutes is a long time to still be able to approve a payment.
The answer is one integer. Give every user a SessionVersion, stamp it into every token
as a claim, and bump it whenever anything that affects authorisation changes — permissions, roles,
disabled status, business membership.
// On validation: is this token's view of the world current?
OnTokenValidated = async ctx =>
{
var userId = ctx.Principal.GetUserId();
var claimed = ctx.Principal.GetInt("sver");
var current = await _versions.GetAsync(userId); // cached 30s
if (claimed < current)
ctx.Fail("stale session"); // -> 401 -> silent refresh
};
A stale token now fails validation, the client's interceptor sees a 401 and performs the silent refresh it was already built to do, and the new access token carries the new claims. The user is not logged out. Their permissions simply change, within one request, and they notice nothing except a button that is no longer there.
The lookup is a single integer by primary key, cached for thirty seconds and evicted on write, so the cost is negligible — and critically, a cache miss is a cheap read rather than a session-ending failure.
The client side nobody writes about
Three things reliably go wrong in the browser, and all three look like server bugs.
Store the session expiry, not the token expiry
The client needs to know when the session ends so it can show a login screen. If you store the access token's expiry instead, the app decides the user is logged out every fifteen minutes and the refresh never gets a chance to run. Store the refresh expiry. The access token's lifetime is an implementation detail the client should never see.
One refresh, not twelve
A page load fires six requests. The token has expired. All six get a 401, all six trigger a refresh, five of them present a token that has just been rotated — and your reuse detection, working exactly as designed, revokes the family and logs the user out.
The refresh must be single-flight: the first 401 starts it, every other request waits on the same promise, and all of them replay once it resolves.
// One in-flight refresh, shared by every waiting request.
private refreshing: Observable<void> | null = null;
refresh(): Observable<void> {
this.refreshing ??= this.http
.post<void>('/user/refresh', {}, { withCredentials: true })
.pipe(
shareReplay(1),
finalize(() => this.refreshing = null)
);
return this.refreshing;
}
Not everything goes through the interceptor
Your HTTP client refreshes on a 401. Three things in a typical app do not use it, and each one fails in its own way:
- Streaming responses over
fetch, because the framework client cannot stream. A 401 there shows a generic error rather than refreshing. Refresh and retry once, explicitly. - WebSocket negotiation. A reconnect handler only covers drops after a successful start, so a 401 on the initial negotiate fails permanently and the connection stays dead until the page reloads. Refresh once on a failed start, then start again.
- Anything built before the interceptor existed, which in every codebase is at least one thing.
The checklist
- Access token measured in minutes, refresh token in days.
- Refresh tokens stored as hashes, rotated on every use, inheriting the original expiry.
- One
FamilyIdper login; a reused token revokes the family. httpOnlyandSecurecookies, with the refresh cookie's path including the path base.- A session version claim, bumped on every authorisation change.
- Client stores the session expiry, refreshes single-flight, and clears state only when the refresh itself fails.
- Rate limits on login, refresh, register and password reset — per IP, not global, or one caller exhausts everybody's budget.
- Logout works with an expired access token. An expired token must still be able to end its own session.