Appearance
Token Lifecycle and Revocation
57. How should JWT expiration be configured?
The short answer
Keep access tokens short, typically 5 to 15 minutes, because they cannot easily be revoked and anyone holding one can use it. Keep refresh tokens longer, from hours to weeks, but store them safely, rotate them on every use, and make them revocable on the server. Always set exp, check it with a few seconds of clock tolerance, and add an absolute limit so a refresh chain cannot go on forever. Pick the numbers by risk: a banking app uses minutes, a note-taking app may keep users signed in for weeks.
| Token | Typical lifetime | Why |
|---|---|---|
| Access token | 5 to 15 minutes | Limits how long a stolen one works |
| ID token | Minutes; used once at login | Only proves the login just happened |
| Refresh token, browser | Hours to days, with an idle timeout | Browsers are exposed to XSS and shared devices |
| Refresh token, mobile app | Weeks to months | Stored in the OS keychain |
| Absolute session limit | 12 hours to 90 days | Forces a full login eventually |
| One-time link tokens | 15 to 60 minutes | Email is not a secure channel |
What "short" buys you, in numbers. If an attacker steals a 15-minute access token, the worst case is 15 minutes of misuse. If you used 24-hour access tokens to avoid building refresh logic, the worst case is a full day, with no way to stop it.
58. What are access tokens and refresh tokens?
The short answer
An access token is what the client shows to an API on each request, usually as Authorization: Bearer …. It is short-lived and says who the user is and what the client may do. A refresh token is a longer-lived credential the client sends only to the auth server, to get a new access token when the old one expires, without making the user log in again. APIs never see refresh tokens. This split means the token that travels everywhere is short-lived, and the long-lived one goes to one well-protected place.
| Access token | Refresh token | |
|---|---|---|
| Sent to | Every API call | Only the auth server's token endpoint |
| Lifetime | Minutes | Hours to months |
| Format | Often a JWT | Usually an opaque random string |
| Checked by | The API, often locally | The auth server, in its database |
| Revocable | Hard, it expires on its own | Yes, delete it from the database |
| If stolen | Misuse until expiry | Misuse until revoked, unless rotation catches it |
Why refresh tokens are usually opaque. The auth server must look them up anyway, to check they have not been revoked or reused. A random string pointing to a database row is simpler and safer than a JWT for that job.
59. What is the lifecycle of a JWT from login through expiration?
The short answer
The user logs in and gets a short-lived access token and a longer-lived refresh token. The client sends the access token to APIs, and each API checks it locally. When it expires, the client trades the refresh token at the auth server for a new pair, and the old refresh token stops working. This repeats until the user logs out, the refresh token expires or is revoked, or the absolute session limit is reached. Then the user must log in again.
60. Why are refresh tokens needed?
The short answer
They resolve a conflict. For security, access tokens must be short-lived, because they are sent everywhere and are hard to revoke. For convenience, users should not log in every 15 minutes. A refresh token lets the client get a fresh access token silently. It also gives the server a control point: on every refresh, the auth server can check whether the user is still active, still allowed, and whether the token was revoked, which a self-contained access token cannot do.
What the auth server can check at each refresh, and an access token cannot:
- Has the user been disabled, or their password changed?
- Did they click "log out of all devices"?
- Have their roles changed? The new access token will carry the new roles.
- Is this refresh token being reused, a sign of theft (question 61)?
- Has the absolute session limit passed?
So the real revocation delay in a token system is the access token's lifetime. That is why it must be short.
61. What is refresh-token rotation, and why is it important?
The short answer
With rotation, every time a refresh token is used, the auth server issues a new refresh token and invalidates the old one. Each refresh token works exactly once. If an old, already-used refresh token is ever presented again, someone has a copy: either the attacker or the real user is replaying it. The server then revokes the whole family of tokens descended from that login, forcing a fresh login. This turns a stolen refresh token from months of silent access into, at most, one use before detection.
ts
async function refresh(presented: string) {
const row = await refreshTokens.findByHash(sha256(presented))
if (!row) throw new HttpError(401, 'Invalid refresh token')
if (row.usedAt) { // (1)
await refreshTokens.revokeFamily(row.familyId)
await alerts.notifyUser(row.userId, 'Suspicious sign-in activity')
throw new HttpError(401, 'Refresh token reused')
}
if (row.expiresAt < Date.now() || row.familyExpiresAt < Date.now()) throw new HttpError(401, 'Session expired') // (2)
const user = await users.findById(row.userId)
if (!user || user.disabled) throw new HttpError(401, 'Account disabled') // (3)
const next = randomBytes(32).toString('base64url')
await db.transaction(async (tx) => { // (4)
await tx.refreshTokens.markUsed(row.id)
await tx.refreshTokens.insert({ hash: sha256(next), userId: user.id, familyId: row.familyId,
expiresAt: Date.now() + 14 * 86_400_000, familyExpiresAt: row.familyExpiresAt })
})
return { accessToken: await issueAccessToken(user), refreshToken: next }
}- Reuse means theft. Revoke the family and tell the user.
- Two expiries: this token's own, and the family's absolute limit set at login.
- A last chance to stop disabled users.
- Mark the old one used and save the new one together, so a crash cannot leave two valid tokens.
A practical wrinkle: races. A browser with two tabs may refresh at the same moment with the same token. The second request then looks like reuse. Many systems allow a grace period of a few seconds in which the just-used token returns the same new pair, instead of revoking everything.
62. How do you securely store and transmit tokens?
The short answer
Always send tokens over HTTPS, in the Authorization header or an HttpOnly cookie, never in URLs. In browsers, the safest choice is not to give JavaScript the tokens at all: keep them on your server and give the browser an HttpOnly, Secure, SameSite session cookie. This is the back end for front end pattern. If a single-page app must hold tokens, keep the access token in memory only, and the refresh token in an HttpOnly cookie scoped to the refresh path. Avoid localStorage, which any script can read. On mobile, use the Keychain on iOS or the Keystore on Android.
| Where | XSS can steal it | CSRF risk | Survives reload | Verdict |
|---|---|---|---|---|
localStorage or sessionStorage | Yes | No | Yes | Avoid for tokens |
| JavaScript memory | Harder, only while open | No | No | Fine for a short access token |
HttpOnly cookie | No | Yes, use SameSite | Yes | Good |
| Server side, browser has a session cookie | Nothing to steal | Use SameSite | Yes | Best for browser apps |
| iOS Keychain, Android Keystore | Not applicable | No | Yes | Right for mobile |
Never put tokens in URLs. URLs end up in browser history, server logs and Referer headers sent to other sites.
63. How can JWTs be revoked?
The short answer
A self-contained JWT stays valid until exp unless the verifier checks something extra. The options, from simplest: keep access tokens short and revoke the refresh token, so the user is out within minutes; keep a deny list of revoked jti values or user IDs, checked on each request; store a token version or "valid after" time per user, and reject tokens issued before it; use introspection, asking the auth server about each token; or rotate the signing key, which kills every token at once, for emergencies. Most systems combine short tokens with a small deny list.
| Method | Revokes | Cost per request | Good for |
|---|---|---|---|
| Short expiry, revoke refresh token | All of a user's sessions within minutes | None | The default |
Deny list of jti | One token immediately | A fast lookup | "Log out this device now" |
| Per-user "valid after" time | Every token for one user | A lookup per user | Password change, account disabled |
| Introspection | Anything, instantly | A network call | High-risk APIs |
| Rotate the signing key | Every token for everyone | None | A leaked signing key |
The "valid after" check:
ts
const payload = await verifyAccessToken(token)
const validAfter = await cache.get(`user:${payload.sub}:valid_after`) // (1)
if (validAfter && payload.iat! < Number(validAfter)) throw new HttpError(401, 'Token revoked') // (2)- One small value per user, set to the current time when they change password or are disabled. It is cached, so the lookup is cheap.
- Reject any token issued before it. All of that user's tokens die at once, and nobody else's are affected.
64. Why is JWT revocation difficult in a stateless system?
The short answer
Because the whole point of a stateless JWT is that the API checks it without asking anyone. It needs only the signature, the key and the clock. Nothing tells the API that this particular token was cancelled five minutes ago. To revoke, the API must consult some shared state, a deny list, a user version or the auth server, and the moment it does, it is no longer stateless and pays for a lookup on every request. You are choosing between instant revocation and zero lookups; you cannot fully have both.
The honest trade-off:
- Fully stateless: fastest, but revocation waits for
exp. Fine ifexpis 5 minutes. - Stateless plus a small cached deny list: almost as fast, revokes immediately, but needs a shared store and cache invalidation.
- Stateful, such as sessions or introspection: instant and simple, but every request does a lookup.
Most real systems choose the second: short tokens, plus a tiny deny list that only holds tokens revoked before their natural expiry. Entries delete themselves once the token would have expired anyway.
65. What is token blacklisting, and what are its trade-offs?
The short answer
Token blacklisting, now usually called a deny list, means recording the IDs, the jti values, of tokens that were revoked before they expired, and rejecting any request whose token is on the list. It gives instant revocation for individual tokens. The trade-offs: every request needs a fast lookup, so the list must live in a shared low-latency store like Redis; the list must be available, or you must decide whether to fail open or closed; and it only works if tokens carry a unique jti. Keep it small by giving each entry an expiry equal to the token's remaining lifetime.
ts
async function revokeToken(payload: { jti: string; exp: number }) {
const secondsLeft = payload.exp - Math.floor(Date.now() / 1000)
if (secondsLeft > 0) await redis.set(`deny:${payload.jti}`, '1', { EX: secondsLeft }) // (1)
}
async function isRevoked(jti: string) {
return (await redis.exists(`deny:${jti}`)) === 1 // (2)
}- The entry lives only as long as the token would have. After that, the token is expired anyway, so Redis deletes the entry and the list never grows forever.
- One fast key lookup per request.
| Good | Bad |
|---|---|
| Instant logout of one token | A lookup on every request |
| Small, because entries expire | Needs a highly available store |
| Simple to explain | Every service must check it, or revocation leaks |
66. What is token introspection?
The short answer
Token introspection, RFC 7662, is an endpoint on the auth server where an API can send a token and ask "is this still valid, and what does it mean?". The server answers with active: true or false, plus details such as sub, scope, client_id and exp. It lets APIs use opaque tokens, random strings that carry no information, and it gives instant revocation, because the auth server knows the current state. The cost is a network call per check, which APIs usually soften with a short cache.
http
POST /oauth/introspect HTTP/1.1
Host: auth.shop.example
Authorization: Basic b3JkZXJzLWFwaTpzM2NyM3Q=
Content-Type: application/x-www-form-urlencoded
token=2YotnFZFEjr1zCsicMWpAAjson
{ "active": true, "sub": "u_42", "client_id": "mobile-app", "scope": "orders:read", "exp": 1793000900 }Reading the exchange: the orders API authenticates itself to the auth server with its own credentials, so not just anyone can probe tokens. A revoked or unknown token returns only { "active": false }, with no reason given.
| Local JWT check | Introspection | |
|---|---|---|
| Network call | No | Yes, per token, unless cached |
| Revocation | At expiry | Immediate |
| Token reveals data to the holder | Yes | No, opaque |
| Auth server outage | APIs keep working | APIs cannot check tokens |
67. How do you design a secure refresh-token system?
The short answer
Make refresh tokens opaque random values, stored hashed in a database with the user, client, device, family ID and two expiries: an idle one and an absolute one. Rotate on every use and detect reuse by revoking the whole family. Bind them to the client they were issued to, and for public clients to the device with DPoP or similar where possible. Deliver them only to the token endpoint: in an HttpOnly cookie scoped to that path for browsers, or the OS keychain for mobile. Revoke them on logout, password change, and account disablement, and list active sessions to the user.
The table behind it:
| Column | Purpose |
|---|---|
token_hash | SHA-256 of the token; the token itself is never stored |
user_id, client_id | Who it belongs to, and which app it was issued to |
family_id | All tokens descended from one login |
device_name, ip, created_at | Shown in "your active sessions" |
expires_at | Idle timeout, extended on each rotation |
family_expires_at | Absolute limit, fixed at login |
used_at, revoked_at | Rotation and revocation state |
The checklist an interviewer wants:
- Opaque, 256 random bits, stored hashed.
- Rotate on every use; revoke the family on reuse (question 61).
- Idle and absolute expiry.
- Sent only to the token endpoint, never to APIs.
- For browsers:
HttpOnly,Secure,SameSite=Strictcookie withPath=/auth/refresh. - Bound to the client, so another app cannot use it; with DPoP, bound to a key on the device, so a copied token is useless elsewhere.
- Revoke on logout, password change, MFA reset and admin action.
- Rate limit the refresh endpoint, and log every refresh for investigations.
DPoP in one sentence. DPoP, RFC 9449, makes the client prove on every request that it holds a private key the token was bound to, so a stolen token without that key is useless.
68. How do you handle token revocation at scale?
The short answer
At scale, you cannot afford a database call per request. So: keep access tokens short, so most revocation is handled by expiry alone; keep the deny list tiny, holding only tokens revoked early, each with an expiry; replicate it to every service through a fast store such as Redis, or push revocation events over a message bus so each service keeps an in-memory copy; use a per-user "valid after" timestamp instead of listing every token; and keep introspection for the few high-risk APIs. For a signing-key leak, rotate the key, which revokes everything at once.
Numbers to quote. With 15-minute access tokens, a deny-list entry is needed for at most 15 minutes. Even with thousands of revocations an hour, the list holds only a few thousand small entries at any moment, easily kept in memory on every instance.
69. What is the difference between session-based and JWT-based authentication?
The short answer
In session-based authentication, the server stores the login state and the client holds a random session ID, usually in a cookie; each request is checked by looking up that ID. In JWT-based authentication, the client holds a signed token containing the claims; each request is checked by verifying the signature, with no lookup. Sessions are easy to revoke and keep data private, but need a shared store. JWTs scale without a lookup and work well across services and for mobile, but are hard to revoke and readable by the holder.
This is the same comparison as question 20, seen from the token side. The differences that decide it:
| Need | Choose |
|---|---|
| Instant logout and "ban this user now" | Sessions, or short JWTs with a deny list |
| Browser app with its own back end | Session cookie |
| Mobile app or third-party API clients | Short-lived JWT access tokens plus refresh tokens |
| Many services verifying identity | JWTs signed with asymmetric keys |
| Holder must not see the data | Sessions, or opaque tokens with introspection |
70. When would you choose stateful sessions over stateless token authentication?
The short answer
Choose stateful sessions when you need immediate control: instant logout, banning users, changing permissions that must apply at once, or strict session limits, as in banking, admin consoles and healthcare. Also choose them for a classic browser app talking to its own back end, where a HttpOnly cookie is the safest storage and a Redis lookup costs under a millisecond. Choose stateless tokens when many independent services or third parties must verify identity without calling you, or for mobile and machine clients.
A sentence to say in the interview. "For our web app I would use server-side sessions in Redis with an HttpOnly cookie, because we need instant logout and the lookup is cheap. For service-to-service calls and our public API I would use short-lived JWTs with asymmetric signing, because those callers should not depend on our session store."
The hybrid most large systems end up with:
- Browser to back end: session cookie, stateful.
- Back end to internal services: short-lived JWT, stateless, created by the back end or a gateway for each call.
- Mobile and partner clients: OAuth access tokens and rotating refresh tokens.