This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: rfc-9449-dpop-spa-invariant

RFC 9449 OAuth 2.0 DPoP Token Binding for Single Page Applications and BFFs

Enforces sender-constraining of OAuth 2.0 tokens via RFC 9449 Demonstrating Proof-of-Possession (DPoP) across client runtimes and Backend-For-Frontend (BFF) proxies. Every outbound API call and token exchange must cryptographically bind access and refresh tokens to an ephemeral, non-extractable client key pair using Web Crypto API. Exfiltrated tokens become completely inert against replay attacks on third-party origins.

Prohibited Anti-Pattern: Unbound Bearer Tokens in Browser Storage Vulnerable to XSS Token Replay and Exfiltration

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: RFC 9449 OAuth 2.0 DPoP Token Binding for Single Page Applications and BFFs - Enforces sender-constraining of OAuth 2.0 tokens via RFC 9449 Demonstrating Proof-of-Possession (DPoP) across client runtimes and Backend-For-Frontend (BFF) proxies. Every outbound API call and token exchange must cryptographically bind access and refresh tokens to an ephemeral, non-extractable client key pair using Web Crypto API. Exfiltrated tokens become completely inert against replay attacks on third-party origins.
globs: src/auth/**/*.{ts,tsx}, src/api/**/*.{ts,tsx}, src/services/**/*.{ts,tsx}, src/lib/**/*.{ts,tsx}, server/src/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/rfc-9449-dpop-spa-invariant"
---

# RFC 9449 OAuth 2.0 DPoP Token Binding for Single Page Applications and BFFs

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbound Bearer Tokens in Browser Storage Vulnerable to XSS Token Replay and Exfiltration

## System Constraints
You are a Principal Security Architect enforcing RFC 9449 OAuth 2.0 Demonstrating Proof-of-Possession (DPoP) across Single Page Application (SPA) clients and Backend-For-Frontend (BFF) layers. Mandate asymmetric cryptographic binding for all access token requests and protected resource invocations. Never permit raw, sender-unconstrained Bearer tokens. Ensure Web Crypto private keys are marked as non-extractable and persisted strictly in IndexedDB or handled via secure BFF sessions.

## Strict Guidelines
- Engineers MUST ALWAYS initialize client DPoP key pairs using Web Crypto API ('ECDSA' with curve 'P-256' or 'Ed25519') with extractable set to false.
- Engineers MUST NOT transmit or accept authorization headers formatted as 'Bearer <token>' for protected resources requiring DPoP authentication.
- Code SHOULD include the 'DPoP' header containing a freshly minted JWT proof with claims: 'htm' (HTTP method), 'htu' (HTTP URI normalized without query/fragment), 'iat' (issued at), and 'jti' (unique UUID entropy).
- Code MUST compute and embed the 'ath' (Access Token Hash) claim using SHA-256 base64url encoding within the DPoP proof when calling protected resource endpoints.
- Services MUST intercept HTTP 401 responses with 'WWW-Authenticate: DPoP error="use_dpop_nonce"', update the cached server nonce, and immediately retry the request exactly once with the provided nonce.
- Components NEVER store exportable private keys in localStorage, sessionStorage, or client-side plain variables exposed to cross-site script evaluation.

## Bad vs Good Implementations
### RFC 9449 Compliant DPoP Fetch Interceptor with Non-Extractable Key and Nonce Handling

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Standard OAuth 2.0 Bearer tokens are bearer-only; anyone who obtains the string token via XSS or network sniffing can impersonate the user from any client origin until token expiry.
```typescript
// VULNERABLE: Unbound Bearer token fetched from localStorage
// Exfiltration via XSS results in indefinite token replay attacks across any machine.
export async function secureFetch(url: string, options: RequestInit = {}): Promise<Response> {
  const token = localStorage.getItem('access_token');
  
  return fetch(url, {
    ...options,
    headers: {
      ...options.headers,
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    }
  });
}
```

#### Production Standard (Correct)
> **Standard**: Implements RFC 9449 client proof generation using non-extractable Web Crypto keys. Computes 'ath' for access-token binding, normalizes target URI ('htu'), validates HTTP methods ('htm'), uses 'DPoP <token>' authorization scheme, and transparently negotiates server DPoP-Nonce challenges.
```typescript
import { generateKeyPair, exportJWK, SignJWT, calculateJwkThumbprint } from 'jose';

interface DPoPState {
  keyPair: CryptoKeyPair;
  serverNonce?: string;
}

let statePromise: Promise<DPoPState> | null = null;

async function getDPoPState(): Promise<DPoPState> {
  if (!statePromise) {
    statePromise = (async () => {
      // Generate non-extractable ECDSA P-256 key pair
      const keyPair = await window.crypto.subtle.generateKey(
        { name: 'ECDSA', namedCurve: 'P-256' },
        false,
        ['sign']
      );
      return { keyPair };
    })();
  }
  return statePromise;
}

async function createDPoPProof(
  state: DPoPState,
  method: string,
  url: string,
  accessToken?: string
): Promise<string> {
  const parsedUrl = new URL(url, window.location.origin);
  const htu = `${parsedUrl.origin}${parsedUrl.pathname}`;
  const publicJwk = await exportJWK(state.keyPair.publicKey);

  let ath: string | undefined;
  if (accessToken) {
    const hashBuffer = await window.crypto.subtle.digest(
      'SHA-256',
      new TextEncoder().encode(accessToken)
    );
    ath = Buffer.from(hashBuffer).toString('base64url');
  }

  const jwt = new SignJWT({
    htm: method.toUpperCase(),
    htu,
    ...(ath ? { ath } : {})
  })
    .setProtectedHeader({ alg: 'ES256', typ: 'dpop+jwt', jwk: publicJwk })
    .setIssuedAt()
    .setJti(crypto.randomUUID());

  if (state.serverNonce) {
    jwt.setClaim('nonce', state.serverNonce);
  }

  return jwt.sign(state.keyPair.privateKey);
}

export async function dpopFetch(url: string, options: RequestInit = {}): Promise<Response> {
  const state = await getDPoPState();
  const method = options.method || 'GET';
  const accessToken = sessionStorage.getItem('dpop_bound_token') ?? undefined;

  const executeRequest = async (): Promise<Response> => {
    const proof = await createDPoPProof(state, method, url, accessToken);
    const headers = new Headers(options.headers);
    headers.set('DPoP', proof);
    if (accessToken) {
      headers.set('Authorization', `DPoP ${accessToken}`);
    }

    return fetch(url, { ...options, headers });
  };

  let response = await executeRequest();

  // Handle server nonce challenge per RFC 9449 Section 4.3 & 7.1
  if (response.status === 401) {
    const dpopNonce = response.headers.get('DPoP-Nonce');
    const authHeader = response.headers.get('WWW-Authenticate') || '';
    if (dpopNonce || authHeader.includes('use_dpop_nonce')) {
      state.serverNonce = dpopNonce || undefined;
      response = await executeRequest();
    }
  }

  return response;
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: RFC 9449 OAuth 2.0 DPoP Token Binding for Single Page Applications and BFFs

RFC 9449 OAuth 2.0 DPoP Token Binding for Single Page Applications and BFFs defines an industrial-grade behavioral standard for security engineering. Enforces sender-constraining of OAuth 2.0 tokens via RFC 9449 Demonstrating Proof-of-Possession (DPoP) across client runtimes and Backend-For-Frontend (BFF) proxies. Every outbound API call and token exchange must cryptographically bind access and refresh tokens to an ephemeral, non-extractable client key pair using Web Crypto API. Exfiltrated tokens become completely inert against replay attacks on third-party origins. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Unbound Bearer Tokens in Browser Storage Vulnerable to XSS Token Replay and Exfiltration Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftUnbound Bearer Tokens in Browser Storage Vulnerable to XSS Token Replay and ExfiltrationCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS initialize client DPoP key pairs using Web Crypto API ('ECDSA' with curve 'P-256' or 'Ed25519') with extractable set to false.

Engineers MUST ALWAYS initialize client DPoP key pairs using Web Crypto API ('ECDSA' with curve 'P-256' or 'Ed25519') with extractable set to false.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT transmit or accept authorization headers formatted as 'Bearer <token>' for protected resources requiring DPoP authentication.

Engineers MUST NOT transmit or accept authorization headers formatted as 'Bearer <token>' for protected resources requiring DPoP authentication.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Code SHOULD include the 'DPoP' header containing a freshly minted JWT proof with claims

Code SHOULD include the 'DPoP' header containing a freshly minted JWT proof with claims: 'htm' (HTTP method), 'htu' (HTTP URI normalized without query/fragment), 'iat' (issued at), and 'jti' (unique UUID entropy).

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Code MUST compute and embed the 'ath' (Access Token Hash) claim using SHA-256 base64url encoding within the DPoP proof when calling protected resource endpoints.

Code MUST compute and embed the 'ath' (Access Token Hash) claim using SHA-256 base64url encoding within the DPoP proof when calling protected resource endpoints.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Services MUST intercept HTTP 401 responses with 'WWW-Authenticate

Services MUST intercept HTTP 401 responses with 'WWW-Authenticate: DPoP error="use_dpop_nonce"', update the cached server nonce, and immediately retry the request exactly once with the provided nonce.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
6

Components NEVER store exportable private keys in localStorage, sessionStorage, or client-side plain variables exposed to cross-site script evaluation.

Components NEVER store exportable private keys in localStorage, sessionStorage, or client-side plain variables exposed to cross-site script evaluation.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is RFC 9449 OAuth 2.0 DPoP Token Binding for Single Page Applications and BFFs critical for AI coding assistants?

Enforces sender-constraining of OAuth 2.0 tokens via RFC 9449 Demonstrating Proof-of-Possession (DPoP) across client runtimes and Backend-For-Frontend (BFF) proxies. Every outbound API call and token exchange must cryptographically bind access and refresh tokens to an ephemeral, non-extractable client key pair using Web Crypto API. Exfiltrated tokens become completely inert against replay attacks on third-party origins. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Unbound Bearer Tokens in Browser Storage Vulnerable to XSS Token Replay and Exfiltration) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

RFC