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.
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.2and Python3.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 location | Survives reload | Impact under XSS | Practical limit |
|---|---|---|---|
localStorage | Yes | Direct read and exfiltration via window.localStorage | Shared across all tabs and scripts; no built-in expiry |
sessionStorage | Same tab only | Immediate read and exfiltration inside the active tab | No cross-tab session sharing; zero XSS protection |
| JS memory (closure) | No | Attacker hooks fetch/XMLHttpRequest or proxies calls | Requires re-authentication on reload; still allows API abuse |
| Web Worker | No | Injected script sends postMessage calls through the worker | Hides raw token string, but cannot stop unauthorized API calls |
| Service Worker | Yes | Attacker triggers normal same-origin requests; SW attaches Bearer | Transparent 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)"]
- 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
HttpOnlysession cookie, and the BFF proxies API calls while injecting theAuthorization: Bearerheader. - 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.
- 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.
| Dimension | Backend for Frontend (BFF) | Token-Mediating Backend | Browser-Based OAuth 2.0 Client |
|---|---|---|---|
| OAuth client type | Confidential Client | Confidential Client | Public Client |
| Artifact in browser | Opaque HttpOnly session cookie | Short-lived Access Token | Access Token (+ Refresh Token) |
| Token theft via XSS | No raw token exfiltration (in-session abuse only) | Access Token exposed (Refresh Token isolated) | Both Access and Refresh Tokens exposed |
| CSRF protection | Mandatory (cookie-authenticated) | Needed on login and token-refresh endpoints | Low risk when using Bearer headers |
| Infra & latency cost | Proxy hop on every API call + shared session store | Backend on token issuance only (direct API calls) | Static CDN hosting only |
| Best fit | Financial apps, admin consoles, sensitive internal SPAs | High-throughput SPAs calling APIs directly | Static 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.
Cookie security and CSRF defense in BFF
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) | Level | Production HTTPS requirement | Threat mitigated |
|---|---|---|---|
Secure (6.1.3.2) | MUST | Send cookie over HTTPS only | Cleartext network interception |
HttpOnly (6.1.3.2) | MUST | Block document.cookie access | Session cookie theft via XSS |
SameSite (6.1.3.2) | SHOULD | Strict (use Lax if cross-site top-level redirects must keep the session) | Cross-site automatic cookie attachment |
Path=/ & omit Domain | SHOULD | Lock cookie to the exact issuing host | Sharing or injection across sibling subdomains |
__Host- / __Host-Http- prefix | SHOULD | Browser enforces Secure, Path=/, and no Domain | Cookie tossing from sibling subdomains |
| CSRF defense (6.1.3.3) | MUST | Custom header (X-CSRF: 1) or anti-CSRF token on state-changing requests + strict CORS | Forged 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 omitsSecureand the__Host-prefix and usesSameSite=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
dictfor sessions andrequests.Sessioninstead of a full browser. Because Keycloak26.8.2marks login flow cookies asSecure; SameSite=None—which modern browsers still send onhttp://localhostas a secure context, whereas Pythonrequestsskips over plain HTTP—the test client cleared thesecureflag onlocalhostcookies to match browser behavior.
Production caveats and checklist
Moving from a single-process demo to production exposes three operational traps:
- 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.
- 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.
- BFF logout vs. IdP SSO session: Clearing the BFF session in
POST /auth/logoutdoesn’t terminate Keycloak’s ownKEYCLOAK_SESSIONcookie. 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_secretorprivate_key_jwt) with PKCES256? - Does the production cookie set
Secure,HttpOnly,SameSite=Strict(orLax),Path=/, omitDomain, 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?