Dev

SPA token security and BFF trade-offs under RFC 10017

Why browser token storage breaks under XSS, how RFC 10017 compares BFF and direct SPA clients, and a five-scenario Keycloak 26.8.2 verification.

SPA token security and BFF trade-offs under RFC 10017

Any token stored where browser JavaScript can reach it breaks down under XSS. In this note, I walk through the three SPA authentication patterns defined in IETF RFC 10017 (BCP 212) (published August 2026), compare when to use or skip a Backend for Frontend (BFF), and verify five security scenarios locally against Keycloak 26.8.2.

This post is based on IETF RFC 10017 / BCP 212 (August 2026) and a local verification setup running Keycloak 26.8.2 and Python 3.14.

Why browser token storage breaks under XSS

When you add OAuth 2.0 or OIDC to a Single Page Application (SPA), the first question is usually where to store tokens. Teams often move tokens out of localStorage into sessionStorage, an in-memory closure, or a Web Worker hoping to close the XSS gap.

IETF RFC 10017 (OAuth 2.0 for Browser-Based Applications) Section 8 explains why that doesn’t solve the root problem. Once attacker-controlled JavaScript runs in the same origin—whether through an XSS bug or a compromised third-party package—no browser storage mechanism can fully isolate OAuth tokens.

Storage locationSurvives reloadImpact under XSSPractical limit
localStorageYesDirect read and exfiltration via window.localStorageShared across all tabs and scripts; no built-in expiry
sessionStorageSame tab onlyImmediate read and exfiltration inside the active tabNo cross-tab session sharing; zero XSS protection
JS memory (closure)NoAttacker hooks fetch/XMLHttpRequest or proxies callsRequires re-authentication on reload; still allows API abuse
Web WorkerNoInjected script sends postMessage calls through the workerHides raw token string, but cannot stop unauthorized API calls
Service WorkerYesAttacker triggers normal same-origin requests; SW attaches BearerTransparent token injection turns the SW into a proxy for attackers

Browsers are also Public Clients by nature. Because an SPA can’t keep a client_secret safe, it relies on Authorization Code + PKCE (S256)—covered in why OAuth 2.1 and RFC 9700 mandate PKCE—and Refresh Token Rotation (RTR) to detect replay after theft. Those controls help, but they don’t prevent an injected script from hijacking an active session or reading tokens exposed to JavaScript.

Three SPA architecture patterns in RFC 10017

RFC 10017 Section 6 ranks browser-based OAuth 2.0 architectures into three patterns from highest to lowest security. The dividing line is simple: how far you keep OAuth tokens away from browser JavaScript.

flowchart TD
    B["Browser SPA"] -->|"HttpOnly cookie"| BFF["BFF Server<br/>(Confidential)"]
    BFF -->|"Code + PKCE"| IDP["Keycloak 26.8.2<br/>(Auth Server)"]
    BFF -->|"Bearer token"| API["Resource API<br/>(JWKS + aud)"]
    BFF -.->|"Store tokens"| STORE["Session Store<br/>(Prod: Redis)"]
  1. Backend for Frontend (BFF, Section 6.1): A server-side BFF acts as a Confidential Client, completes Authorization Code + PKCE, and stores tokens only on the server. The browser talks to the BFF using an opaque HttpOnly session cookie, and the BFF proxies API calls while injecting the Authorization: Bearer header.
  2. Token-Mediating Backend (Section 6.2): A confidential backend handles token exchange and keeps the Refresh Token on the server, but returns a short-lived Access Token to the browser so the SPA can call Resource Servers directly.
  3. Browser-Based OAuth 2.0 Client (Section 6.3): The browser acts as a Public Client with no backend tier, running the OAuth flow and holding tokens directly.
DimensionBackend for Frontend (BFF)Token-Mediating BackendBrowser-Based OAuth 2.0 Client
OAuth client typeConfidential ClientConfidential ClientPublic Client
Artifact in browserOpaque HttpOnly session cookieShort-lived Access TokenAccess Token (+ Refresh Token)
Token theft via XSSNo raw token exfiltration (in-session abuse only)Access Token exposed (Refresh Token isolated)Both Access and Refresh Tokens exposed
CSRF protectionMandatory (cookie-authenticated)Needed on login and token-refresh endpointsLow risk when using Bearer headers
Infra & latency costProxy hop on every API call + shared session storeBackend on token issuance only (direct API calls)Static CDN hosting only
Best fitFinancial apps, admin consoles, sensitive internal SPAsHigh-throughput SPAs calling APIs directlyStatic public apps with lower risk profiles

When not to use BFF

RFC 10017 places BFF at the top of the security hierarchy, but it isn’t the right default for every SPA. You should consider Token-Mediating Backend or a Browser-Based OAuth 2.0 Client in three common cases:

  • Pure static hosting: If your frontend ships to GitHub Pages or S3 + CloudFront with no server runtime, introducing a BFF adds a new stateful tier, deployment pipeline, and availability surface.
  • High-bandwidth direct API calls: If the browser streams large payloads or talks to multiple API domains, routing every request through a BFF adds latency and proxy bandwidth cost. Keeping only the Refresh Token on the backend (Token-Mediating Backend) often strikes a better balance.
  • Low-risk apps without backend ops capacity: When the data sensitivity is low and the team can’t operate a shared session store like Redis, a Public Client with PKCE S256, short Access Token lifetimes, and a strict Content-Security-Policy (CSP) is easier to run cleanly.

Moving tokens out of JavaScript shifts the browser boundary onto session cookies. Weak cookie flags or missing CSRF checks undo most of the benefit of adopting a BFF.

RFC 10017 Section 6.1.3 sets clear requirements for BFF implementations. The BFF MUST act as a Confidential Client and MUST use the Authorization Code Grant following RFC 9700 Section 2.1.1 (Section 6.1.3.1). Cookie and CSRF rules break down as follows:

Control (RFC 10017)LevelProduction HTTPS requirementThreat mitigated
Secure (6.1.3.2)MUSTSend cookie over HTTPS onlyCleartext network interception
HttpOnly (6.1.3.2)MUSTBlock document.cookie accessSession cookie theft via XSS
SameSite (6.1.3.2)SHOULDStrict (use Lax if cross-site top-level redirects must keep the session)Cross-site automatic cookie attachment
Path=/ & omit DomainSHOULDLock cookie to the exact issuing hostSharing or injection across sibling subdomains
__Host- / __Host-Http- prefixSHOULDBrowser enforces Secure, Path=/, and no DomainCookie tossing from sibling subdomains
CSRF defense (6.1.3.3)MUSTCustom header (X-CSRF: 1) or anti-CSRF token on state-changing requests + strict CORSForged requests from cross-site pages or sibling subdomains

A common trap is assuming SameSite=Strict or Lax alone eliminates CSRF. Two apps on app.example.com and legacy.example.com are different origins, but browsers treat them as the same site (same eTLD+1). Requiring a custom header like X-CSRF: 1 on state-changing methods (POST, PUT, DELETE) forces a CORS preflight check, blocking simple form posts and unauthorized cross-origin calls.

The local HTTP demo below runs on http://localhost, so it omits Secure and the __Host- prefix and uses SameSite=Lax. In production over HTTPS, always emit __Host-bff_session=<id>; Secure; HttpOnly; SameSite=Strict; Path=/.

Verifying five BFF scenarios with Keycloak 26.8.2

To verify the full HTTP sequence without mocks, I ran Keycloak 26.8.2 in Docker (localhost:18580), a minimal Python BFF (localhost:18581), and a Resource API (localhost:18582). The Realm and Audience Mapper layout follows the same setup I documented in setting up Keycloak 26 for OIDC token flows and production.

1) Confidential Client and Audience Mapper in Keycloak

Inside demo-realm, bff-client is configured with publicClient: false, PKCE S256 enforcement, and a custom demo-api Audience Mapper so the Access Token carries aud: "demo-api".

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
{
  "clientId": "bff-client",
  "publicClient": false,
  "clientAuthenticatorType": "client-secret",
  "secret": "<BFF_CLIENT_SECRET>",
  "standardFlowEnabled": true,
  "implicitFlowEnabled": false,
  "directAccessGrantsEnabled": false,
  "redirectUris": ["http://localhost:18581/auth/callback"],
  "attributes": {
    "pkce.code.challenge.method": "S256"
  },
  "protocolMappers": [
    {
      "name": "demo-api-audience",
      "protocol": "openid-connect",
      "protocolMapper": "oidc-audience-mapper",
      "config": {
        "included.custom.audience": "demo-api",
        "id.token.claim": "false",
        "access.token.claim": "true"
      }
    }
  ]
}

2) BFF session isolation, CSRF check, and Resource API JWKS validation

In bff_server.py, /auth/callback stores the exchanged tokens in server memory and sends only a 32-byte opaque session ID cookie to the browser. On POST /api/orders, the BFF rejects requests missing X-CSRF: 1 before attaching Authorization: Bearer to the upstream call.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# bff_server.py (core handler excerpt, Python 3.14 + requests)
session_id = secrets.token_urlsafe(32)
SESSIONS[session_id] = {
    "access_token": tokens["access_token"],
    "refresh_token": tokens.get("refresh_token"),
    "id_token": tokens["id_token"],
    "sub": id_claims.get("sub"),
    "preferred_username": id_claims.get("preferred_username"),
}
# Production HTTPS: "__Host-bff_session=<sid>; Secure; HttpOnly; SameSite=Strict; Path=/"
cookie_header = f"bff_session={session_id}; HttpOnly; SameSite=Lax; Path=/"

# POST /api/orders: require custom CSRF header before proxying with Bearer token
if self.headers.get("X-CSRF") != "1":
    self._send_json(403, {"error": "csrf_header_required"})
    return
upstream = requests.post(
    f"{RESOURCE_API_URL}/orders",
    data=raw,
    headers={"Authorization": f"Bearer {sess['access_token']}", "Content-Type": "application/json"},
    timeout=10,
)

resource_api.py ignores cookies completely. It expects a Bearer JWT and validates the RS256 signature against Keycloak’s JWKS endpoint along with aud="demo-api" and iss.

1
2
3
4
5
6
7
8
9
10
11
12
13
# resource_api.py (PyJWT + cryptography)
jwk_client = PyJWKClient(f"{KEYCLOAK_ISSUER}/protocol/openid-connect/certs")

def verify_bearer(auth_header: str) -> dict:
    token = auth_header[len("Bearer "):].strip()
    signing_key = jwk_client.get_signing_key_from_jwt(token)
    return jwt.decode(
        token,
        signing_key.key,
        algorithms=["RS256"],
        audience="demo-api",
        issuer=KEYCLOAK_ISSUER,
    )

3) Observed results across five scenarios

Running the verification client against the live Keycloak 26.8.2 container (start-dev --import-realm) and both Python servers produced the following masked output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
=== [Scenario 1] BFF Login (Authorization Code + PKCE S256 + Confidential Client) ===
BFF /auth/callback status=200, body={"authenticated": true, "user": "alice"}
BFF /auth/callback Set-Cookie=bff_session=UbJk4_...<masked:43chars>; HttpOnly; SameSite=Lax; Path=/
PASS Scenario 1: HttpOnly=True, SameSite=Lax, no JWT/tokens in BFF cookie or response.

=== [Scenario 2] Browser -> BFF GET /api/orders (Cookie only, server injects Bearer) ===
BFF GET /api/orders status=200, body={"owner": "44cdd5f2-deae-472f-b6e3-590323fa1fea", "preferred_username": "alice", "aud": "demo-api", "orders": [...]}
PASS Scenario 2: Resource API verified RS256 JWKS + aud='demo-api'; browser received data without seeing any JWT.

=== [Scenario 3] Browser -> Resource API (18582) direct call (Cookie only, no Bearer) ===
Direct Resource API GET /orders status=401, body={"error": "missing_bearer_token"}

=== [Scenario 4] CSRF Defense on POST /api/orders ===
POST /api/orders (no X-CSRF header) status=403, body={"error": "csrf_header_required"}
POST /api/orders (with X-CSRF: 1)   status=200, body={"created": true, "order_id": "ORD-103", "owner": "44cdd5f2-deae-472f-b6e3-590323fa1fea", "preferred_username": "alice", "item": "Monitor"}

=== [Scenario 5] BFF Logout (POST /auth/logout) + Replay Old Cookie ===
POST /auth/logout status=200, Set-Cookie=bff_session=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0
Replay GET /api/orders with old bff_session cookie status=401, body={"error": "unauthenticated"}

Every boundary behaved as designed: no JWT (eyJ...) appeared in the browser cookie or JSON body, direct cookie calls to the Resource API returned 401, missing X-CSRF headers returned 403, and deleting the server session with Max-Age=0 invalidated replayed cookies immediately.

This local run used an in-memory Python dict for sessions and requests.Session instead of a full browser. Because Keycloak 26.8.2 marks login flow cookies as Secure; SameSite=None—which modern browsers still send on http://localhost as a secure context, whereas Python requests skips over plain HTTP—the test client cleared the secure flag on localhost cookies to match browser behavior.

Production caveats and checklist

Moving from a single-process demo to production exposes three operational traps:

  1. A BFF doesn’t fix XSS: Keeping tokens off the browser stops raw token exfiltration and post-session abuse, but an active XSS payload can still call BFF endpoints while the tab stays open. You still need strict CSP headers, output encoding, and dependency hygiene.
  2. Multi-instance sessions and refresh races: Running more than one BFF instance requires a shared session store such as Redis. When multiple tabs hit the BFF right as an Access Token expires, coordinate server-side Refresh Token renewal with a per-session lock or single-flight guard so concurrent refreshes don’t collide.
  3. BFF logout vs. IdP SSO session: Clearing the BFF session in POST /auth/logout doesn’t terminate Keycloak’s own KEYCLOAK_SESSION cookie. If users must be signed out everywhere, wire up OIDC RP-Initiated Logout or Back-Channel Logout alongside local session deletion.

Before shipping a BFF to production, run through this checklist:

  • Does the BFF authenticate as a Confidential Client (client_secret or private_key_jwt) with PKCE S256?
  • Does the production cookie set Secure, HttpOnly, SameSite=Strict (or Lax), Path=/, omit Domain, and use the __Host- prefix?
  • Do state-changing endpoints enforce a custom CSRF header or anti-CSRF token alongside strict CORS origins?
  • Are shared session storage (Redis) and synchronized server-side Refresh Token renewal in place for multiple instances?
  • Did you confirm that your app’s risk profile justifies operating a stateful proxy tier instead of static hosting?

References

This specification details the threats, attack consequences, security considerations, and best practices that must be taken into account when developing browser-based applications that use OAuth 2.0.
This document describes best current security practice for OAuth 2.0. It updates and extends the threat model and security advice given in RFCs 6749, 6750, and 6819 to incorporate practical experiences gathered since OAuth 2.0 was published and covers new threats relevant due to the broader application of OAuth 2.0. Further, it deprecates some modes of operation that are deemed less secure or even insecure.
This post is licensed under CC BY 4.0 by the author.