Skip to content

Interview PrepTokens · Advanced

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.

TokenTypical lifetimeWhy
Access token5 to 15 minutesLimits how long a stolen one works
ID tokenMinutes; used once at loginOnly proves the login just happened
Refresh token, browserHours to days, with an idle timeoutBrowsers are exposed to XSS and shared devices
Refresh token, mobile appWeeks to monthsStored in the OS keychain
Absolute session limit12 hours to 90 daysForces a full login eventually
One-time link tokens15 to 60 minutesEmail 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 tokenRefresh token
Sent toEvery API callOnly the auth server's token endpoint
LifetimeMinutesHours to months
FormatOften a JWTUsually an opaque random string
Checked byThe API, often locallyThe auth server, in its database
RevocableHard, it expires on its ownYes, delete it from the database
If stolenMisuse until expiryMisuse 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.

clientauth serverAPI⑥ logout or revoke: delete the refresh token family① login: A1 + R1② Bearer A1, for 15 min③ A1 expired: send R1④ A2 + R2; R1 now used⑤ Bearer A2
Short tokens, renewed quietly. ① Login gives a pair. ② The access token does the work. ③ and ④ A refresh swaps the old pair for a new one, and the old refresh token stops working. ⑤ Work continues. ⑥ Revoking the refresh token ends the chain; the last access token dies within minutes.

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:

  1. Has the user been disabled, or their password changed?
  2. Did they click "log out of all devices"?
  3. Have their roles changed? The new access token will carry the new roles.
  4. Is this refresh token being reused, a sign of theft (question 61)?
  5. 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.

userattacker, has R1auth server · family F7 from one loginR1usedR2currentR3 nextR1 reused: revoke family F7everyone logs in again · alert the user① refresh R1② replays R1
A refresh token is a single-use ticket. ① The real user swaps R1 for R2. ② When the stolen R1 shows up again, the server knows a copy exists, but not who holds it, so it ends the entire family. The attacker's access ends at that moment.
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 }
}
  1. Reuse means theft. Revoke the family and tell the user.
  2. Two expiries: this token's own, and the family's absolute limit set at login.
  3. A last chance to stop disabled users.
  4. 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.

WhereXSS can steal itCSRF riskSurvives reloadVerdict
localStorage or sessionStorageYesNoYesAvoid for tokens
JavaScript memoryHarder, only while openNoNoFine for a short access token
HttpOnly cookieNoYes, use SameSiteYesGood
Server side, browser has a session cookieNothing to stealUse SameSiteYesBest for browser apps
iOS Keychain, Android KeystoreNot applicableNoYesRight for mobile
browseronly an HttpOnlysession cookieBFF, your serverholds access tokenand refresh tokenrefreshes when neededAPIsidentity providercookieBearerrefresh
Keep tokens where scripts cannot reach. The browser only ever has a cookie that JavaScript cannot read. Your back end swaps it for real tokens on each API call. An XSS bug can still act while the page is open, but it cannot steal a token to use later from somewhere else.

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.

MethodRevokesCost per requestGood for
Short expiry, revoke refresh tokenAll of a user's sessions within minutesNoneThe default
Deny list of jtiOne token immediatelyA fast lookup"Log out this device now"
Per-user "valid after" timeEvery token for one userA lookup per userPassword change, account disabled
IntrospectionAnything, instantlyA network callHigh-risk APIs
Rotate the signing keyEvery token for everyoneNoneA 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)
  1. 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.
  2. 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:

  1. Fully stateless: fastest, but revocation waits for exp. Fine if exp is 5 minutes.
  2. Stateless plus a small cached deny list: almost as fast, revokes immediately, but needs a shared store and cache invalidation.
  3. 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)
}
  1. 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.
  2. One fast key lookup per request.
GoodBad
Instant logout of one tokenA lookup on every request
Small, because entries expireNeeds a highly available store
Simple to explainEvery 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=2YotnFZFEjr1zCsicMWpAA
json
{ "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 checkIntrospection
Network callNoYes, per token, unless cached
RevocationAt expiryImmediate
Token reveals data to the holderYesNo, opaque
Auth server outageAPIs keep workingAPIs 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:

ColumnPurpose
token_hashSHA-256 of the token; the token itself is never stored
user_id, client_idWho it belongs to, and which app it was issued to
family_idAll tokens descended from one login
device_name, ip, created_atShown in "your active sessions"
expires_atIdle timeout, extended on each rotation
family_expires_atAbsolute limit, fixed at login
used_at, revoked_atRotation and revocation state

The checklist an interviewer wants:

  1. Opaque, 256 random bits, stored hashed.
  2. Rotate on every use; revoke the family on reuse (question 61).
  3. Idle and absolute expiry.
  4. Sent only to the token endpoint, never to APIs.
  5. For browsers: HttpOnly, Secure, SameSite=Strict cookie with Path=/auth/refresh.
  6. 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.
  7. Revoke on logout, password change, MFA reset and admin action.
  8. 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.

admindisable u_42auth serveru_42 valid_after =nowmessage busorders APImemory cachebilling APImemory cachereports APImemory cache
Push the change, check locally. The revocation is announced once. Every API instance updates its own memory, so checking a request costs nothing extra. If an instance misses the event, the short token lifetime still limits the damage.

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:

NeedChoose
Instant logout and "ban this user now"Sessions, or short JWTs with a deny list
Browser app with its own back endSession cookie
Mobile app or third-party API clientsShort-lived JWT access tokens plus refresh tokens
Many services verifying identityJWTs signed with asymmetric keys
Holder must not see the dataSessions, 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:

  1. Browser to back end: session cookie, stateful.
  2. Back end to internal services: short-lived JWT, stateless, created by the back end or a gateway for each call.
  3. Mobile and partner clients: OAuth access tokens and rotating refresh tokens.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
Authentication & Identity
Cookies & sessions
Authentication
Tokens
OAuth & OIDC
Enterprise SSO
Directories
Authorization
Other topics
Nothing picked yet