Join our Newsletter — 33% off our NHI Course
Home› Guides› OAuth for Browser-Based Applications and the BFF Pattern…
Guide Authentication

OAuth for Browser-Based Applications and the BFF Pattern Guide: Keeping Tokens Out of the Browser

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, edited by Lalit Choda Updated 27 October 2026 13 min read
On this page

Any token a single-page application can read, malicious JavaScript running in that application can read too. Cross-site scripting, a compromised npm dependency or a poisoned third-party script runs with the same privileges as the application's own code, so the question "where should my SPA store tokens?" has no safe answer while the tokens are in the browser at all. RFC 10017, OAuth 2.0 for Browser-Based Applications, published as an IETF Best Current Practice in August 2026, sets out three architectures and ranks them, with the backend-for-frontend (BFF) pattern first. This guide explains the threat model behind that ranking, how to build a BFF correctly, when the other two patterns are acceptable, and how to migrate an existing SPA. It is for front-end and platform engineers, identity architects and application security reviewers.

Key takeaways

  • Malicious JavaScript can always ask for new tokens. RFC 10017 shows that an attacker running code in the page can start a fresh silent flow in a hidden iframe; short lifetimes, rotation and DPoP do not stop that, only a confidential back end does.
  • BFF is the recommended pattern for business and sensitive applications. Tokens stay on the server, the browser holds only an HttpOnly, Secure session cookie, and the BFF proxies API calls.
  • A BFF moves the problem to CSRF and proxy abuse. It must enforce CSRF defences, strict cookie attributes and an explicit allowlist of downstream hosts and paths.
  • There is no safe browser storage for tokens. localStorage, sessionStorage, IndexedDB, in-memory and worker storage differ only in exposure; none stops exfiltration by code running in the app.
  • If you must run OAuth in the browser, harden it fully. Authorisation code with PKCE, exact redirect URIs, rotated or DPoP-bound refresh tokens with an absolute lifetime, and no implicit or password grants.

The threat model: malicious JavaScript

RFC 10017 starts from one premise: malicious JavaScript has the same privileges as the legitimate application code (ATT&CK T1059.007 JavaScript, with T1185 Browser Session Hijacking as the outcome). It then lists four attack scenarios, and which architecture stops each one is what drives the ranking.

Scenario (RFC 10017 section)What the attacker doesBrowser-based clientToken-mediating backendBFF
Single-execution token theft (5.1.1)Reads tokens once and sends them awayExposed; limited by short lifetimes, rotation, sender-constrainingAccess token exposed; refresh token safeNot possible: no tokens in browser
Persistent token theft (5.1.2)Keeps polling storage to collect each new tokenExposed; rotation alone does not stop itAccess tokens exposedNot possible
Acquisition of new tokens (5.1.3)Runs a new silent authorisation flow in a hidden iframeExposed; lifetimes, rotation and DPoP do not helpMitigated: the flow needs the confidential back endMitigated
Proxying requests via the user's browser (5.1.4)Uses the victim's browser to call APIs while the page is openExposedExposedExposed: no architecture prevents this

The last row matters: a BFF stops token theft, not XSS. An attacker who controls the page can still act as the user while the page is open. XSS prevention, Content Security Policy and dependency control remain essential. See the Cross-Site Scripting (XSS) Prevention Guide and the Client-Side Security Guide.

The three architectures compared

AspectBackend for Frontend (6.1)Token-mediating backend (6.2)Browser-based OAuth client (6.3)
OAuth client typeConfidential (back end)Confidential (back end)Public (JavaScript)
Access token locationServer onlyBrowserBrowser
Refresh token locationServer onlyServer sessionBrowser
API callsBrowser to BFF, BFF to APIBrowser direct to APIBrowser direct to API
Main residual riskCSRF, proxy abuse, BFF compromiseAccess token theftAll four scenarios
RFC 10017 positionStrongly recommended for business, sensitive and personal-data applicationsConsider a full BFF first; use only when proxying is not possibleLeast secure; acceptable only with full hardening and low-risk data
Operational costHighest: stateful server, latency, scalingMediumLowest: static hosting

Choosing between them

  • Choose a BFF when: the app handles personal data, money, admin functions or business records, or when a token leak would be reportable. This covers most enterprise SPAs, including internal line-of-business tools that look low risk but expose customer or employee records.
  • Choose a token-mediating backend when: APIs must be called directly from the browser for latency or architecture reasons (for example many third-party APIs with CORS), and the access tokens are short-lived and narrowly scoped.
  • Accept a pure browser client only when: data is low sensitivity, there is no server component you can run, and the authorisation server enforces PKCE, refresh token rotation or DPoP, and absolute refresh lifetimes.
  • Consider no OAuth in the browser at all: RFC 10017 section 7.1 notes that a first-party app served from a single domain can use ordinary server-side session cookies instead of access tokens.
  • Small teams: use a framework or gateway that provides a BFF (many web frameworks and API gateways do) rather than writing one. Large organisations: provide a shared, reviewed BFF component or platform service so each team does not reinvent cookie, CSRF and proxy controls.

Building a BFF correctly

RFC 10017 section 6.1.3 sets specific requirements. Treat these as the minimum.

ControlRequirement (RFC 10017)Practical setting
Client typeMUST be a confidential clientAuthenticate to the AS with private_key_jwt or mTLS rather than a shared secret where possible
Cookie securityMUST set Secure and HttpOnly; SHOULD use SameSite=Strict, path /, no Domain, __Host- prefixSet-Cookie: __Host-session=...; Path=/; Secure; HttpOnly; SameSite=Strict
Cookie contentsClient-side session cookies SHOULD be encryptedPrefer an opaque session ID pointing to server-side storage; if tokens are stored in the cookie, encrypt them
CSRFMUST implement CSRF defence; SameSite alone is insufficient across same-site subdomainsRequire a custom request header (for example X-CSRF: 1) enforced via CORS preflight, or anti-forgery tokens
Outbound requestsMUST restrict to an explicit allowlist of hosts and pathsMap routes such as /api/orders/* to one upstream; never forward to arbitrary URLs
PrivacyBFF sees all trafficDo not hand the BFF to a third party without assessing that exposure
  1. Login: the browser navigates to /bff/login; the BFF runs the authorisation code flow with PKCE and state, receives tokens at its redirect URI, stores them server-side and sets the session cookie.
  2. API calls: the SPA calls same-origin /api/... with the custom CSRF header; the BFF looks up the session, attaches the access token, refreshes it when needed, and forwards only to allowlisted upstreams.
  3. User info: expose a /bff/user endpoint that returns the claims the UI needs, so the SPA never needs the ID Token.
  4. Logout: /bff/logout clears the server session, revokes the refresh token, and redirects to the OP's end_session_endpoint. Register a back-channel logout URI so OP-initiated logouts also clear the BFF session. See the OpenID Connect Logout and Session Management Guide.
  5. Token handling on the server: keep tokens out of logs, encrypt them at rest in the session store, and sender-constrain them where the AS supports it. See the DPoP Guide.

If the SPA stays a public OAuth client

Section 6.3 sets the requirements for a browser-based client. Section 7 deprecates the implicit grant (the AS must not return access tokens in the authorisation response) and says the resource owner password credentials grant must not be used.

  • PKCE: the client MUST use PKCE and the AS MUST enforce it; RFC 9700 recommends the S256 method.
  • CSRF on the redirect: protect with PKCE, state or nonce.
  • No client secrets: shared secrets MUST NOT be used for a browser client; anything shipped to the browser is public.
  • Redirect URIs: exact string matching only.
  • postMessage: verify message origins whenever tokens or codes cross windows.
  • Refresh tokens: the AS MUST rotate them on each use or sender-constrain them, MUST set a maximum lifetime or inactivity expiry, MUST NOT extend lifetime beyond the original expiry when rotating, and SHOULD tie refresh lifetime to the user's authenticated session. See the OAuth Refresh Token Rotation and Expiry Guide.
  • DPoP: with a non-extractable key, stolen access tokens can only be abused online in the user's browser; DPoP does not stop an attacker starting a new flow and binding tokens to their own key.

Browser token storage, ranked by exposure

Storage (RFC 10017 section 8)ExposureNotes
JavaScript-set cookiesHighNot recommended: readable by script and sent automatically to the server
localStorageHighPersistent, shared across tabs, readable by any same-origin script
IndexedDBHighPersistent and shared with service workers; asynchronous, preferred over localStorage
sessionStorageMediumTied to one tab and its lifetime
In-memory (closure)LowerLost on reload; closures can be undermined, for example by prototype poisoning
Web Worker or Service WorkerLower for refresh tokenCan isolate the refresh token; access tokens still reach the app; cannot stop new flows

The RFC's conclusion is that none of these fully prevents exfiltration once an attacker can run code in the application. It also rejects using a Service Worker as the OAuth client (section 7.4), because an attacker can unregister it and run a new flow in a fresh context. See the Browser Storage Security Guide.

Migrating an SPA to a BFF

  1. Inventory: list each SPA, its OAuth client ID, grant types, where it stores tokens, and which APIs it calls directly. Flag any using the implicit grant or response_type=token.
  2. Stand up the BFF beside the SPA: serve it on the same origin (for example app.example.com/bff) so the session cookie can be __Host- prefixed and SameSite=Strict.
  3. Register a new confidential client: do not convert the public client in place; a new client ID makes rollback and audit simple.
  4. Route one API through the BFF first: switch a low-risk read API, verify CSRF enforcement (requests without the custom header must fail) and the upstream allowlist.
  5. Move login and remaining APIs: then remove all token handling code from the SPA, including storage reads and Authorization header injection.
  6. Retire the public client: disable the old client ID at the AS and revoke its outstanding refresh tokens.
  7. Rollback: keep the old client disabled but not deleted for one release cycle, behind a feature flag in the SPA.

Detection and measurement

Monitor the BFF for requests missing the CSRF header, attempts to reach non-allowlisted upstream paths, session cookies presented from a new IP or user agent mid-session, and spikes in refresh activity per session. At the AS, alert on silent (prompt=none) authorisation requests for public clients at unusual rates, which can indicate the "acquisition of new tokens" attack. Use Content Security Policy reporting to see unexpected script sources.

  • Token-free browsers: share of sensitive SPAs using a BFF, target 100%.
  • Implicit grant usage: number of clients still allowed response_type=token, target zero.
  • CSRF rejection rate: requests rejected for missing the CSRF header, trended over time.
  • Refresh token absolute lifetime: maximum configured lifetime for browser clients, kept within the user session length.
  • CSP violation reports: third-party script violations per week, as a leading indicator of injection.

Framework mapping

FrameworkReferenceRelevance
OWASP ASVS 5.0V10.1.1 tokens only sent to components that need them (BFF); V3.3.1, V3.3.2, V3.3.4 cookie attributes; V3.4.3 Content Security Policy; V10.2.1 CSRF protection in the code flow; V10.4.5 refresh token replay; V10.4.6 PKCEDirect verification requirements for this architecture
NIST SP 800-53 Rev. 5SC-23 Session Authenticity; IA-5 Authenticator Management; SC-8 Transmission Confidentiality and IntegritySession protection, token handling, transport
NIST CSF 2.0PR.AA-03; PR.AA-05Authentication and enforced authorisation
ISO/IEC 27001:2022 Annex AA.8.5 Secure authentication; A.8.28 Secure codingSession and token handling in application design
MITRE ATT&CKT1059.007 JavaScript; T1185 Browser Session Hijacking; T1528 Steal Application Access TokenThe attack chain the BFF breaks

Common failure patterns

  • "HttpOnly cookie" without CSRF defence: moving tokens to a cookie and stopping there swaps token theft for request forgery.
  • Open proxy BFF: a BFF that forwards any path or host turns the session into a server-side request forgery tool with the user's token attached.
  • BFF that still returns the access token: a /token endpoint "for convenience" quietly converts the BFF back into a token-mediating backend.
  • Refresh tokens in localStorage with no absolute lifetime: one XSS yields indefinite access, and sliding expiry keeps it alive.
  • Treating the BFF as XSS protection: the attacker can still proxy requests through the open page; script integrity and CSP remain required.
  • Third-party scripts with full page access: analytics, chat and tag-manager scripts run with the app's privileges. See the Same-Origin Policy and Browser Security Model Guide.

Lessons from incidents

The malicious-JavaScript premise is not theoretical. In the Lottie Player npm compromise, attackers used a developer's stolen npm publish token to release poisoned versions of a widely embedded player library. Sites that loaded it from public CDNs on the latest tag served the attacker's script to their visitors without changing anything themselves, and that script ran with full page privileges. Any OAuth token readable in those pages would have been in reach. Three lessons follow for browser OAuth design:

  • Assume third-party code will one day turn hostile: pin versions, use Subresource Integrity for CDN scripts, and keep tokens where page scripts cannot reach them.
  • Limit what a hijacked page can do: even with a BFF, scope API routes narrowly and require re-authentication for high-risk actions, because the proxying scenario remains open.
  • Protect the publishing path: the root cause was a non-human credential, a publish token. See the npm Tokens Security Guide.

Practitioner checklist

  • Classify every SPA by data sensitivity and record its OAuth architecture.
  • Use a BFF for all business, sensitive and personal-data applications.
  • Set session cookies with __Host-, Secure, HttpOnly, SameSite=Strict and Path=/.
  • Enforce a CSRF custom header or anti-forgery token on every state-changing BFF route.
  • Restrict BFF forwarding to an explicit allowlist of upstream hosts and paths.
  • Disable the implicit and password grants for every browser client at the AS.
  • For remaining public clients, enforce PKCE S256, exact redirect URIs, rotated or DPoP-bound refresh tokens and an absolute refresh lifetime.
  • Deploy a strict Content Security Policy and review third-party scripts.
  • Wire BFF logout to refresh token revocation and OIDC back-channel logout.

Standards and references

Related NHI Mgmt Group resources: Token and Session Security Guide · Browser Storage Security Guide · OAuth Refresh Token Rotation and Expiry Guide · DPoP Guide · OAuth for Native and Mobile Apps Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

NHIMG Editorial Note
Researched and written by the NHI Mgmt Group editorial team using AI tools, under the editorial direction of Lalit Choda. Facts are drawn from the sources listed on this page and checked by our automated quality process. Last updated 27 October 2026. Spotted an error? Use our contact page.
NHI Mgmt Group, the independent authority on Non-Human Identity, IAM and Agentic AI security. nhimg.org

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick the PDF box to continue.