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

OAuth 2.0 RFC 9449 DPoP Ephemeral Cryptographic Binding

Enforces RFC 9449 Demonstrating Proof-of-Possession (DPoP) at application boundaries to bind OAuth access and refresh tokens to non-extractable client key pairs. Prevents token replay and unauthorized credential reuse by requiring signed ephemeral proof JWTs with strict HTTP method, URI normalization, token hash ('ath'), and server nonce verification on every request. Replaces traditional bearer authentication with sender-constrained token validation across all client-server communications.

Prohibited Anti-Pattern: Transmitting Unbound Bearer Tokens or Reusing Static DPoP Proofs Without Nonce and ATH Validation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OAuth 2.0 RFC 9449 DPoP Ephemeral Cryptographic Binding - Enforces RFC 9449 Demonstrating Proof-of-Possession (DPoP) at application boundaries to bind OAuth access and refresh tokens to non-extractable client key pairs. Prevents token replay and unauthorized credential reuse by requiring signed ephemeral proof JWTs with strict HTTP method, URI normalization, token hash ('ath'), and server nonce verification on every request. Replaces traditional bearer authentication with sender-constrained token validation across all client-server communications.
globs: src/auth/**/*.{ts,tsx,js}, src/api/**/*.{ts,tsx,js}, src/services/**/*.{ts,tsx,js}, src/lib/http/**/*.{ts,tsx,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/rfc-9449-dpop-ephemeral-binding-standard"
---

# OAuth 2.0 RFC 9449 DPoP Ephemeral Cryptographic Binding

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Transmitting Unbound Bearer Tokens or Reusing Static DPoP Proofs Without Nonce and ATH Validation

## System Constraints
You are a Principal Security Architect enforcing RFC 9449 OAuth 2.0 Demonstrating Proof-of-Possession (DPoP). Every outbound authenticated HTTP request MUST use DPoP proofs signed by a non-extractable client key. Reject plain Bearer tokens, validate 'ath' calculation when presenting access tokens, enforce 'htm' and 'htu' canonicalization without query parameters, and mandate handling of 'DPoP-Nonce' challenge loops.

## Strict Guidelines
- Engineers MUST ALWAYS generate non-extractable asymmetric key pairs (ES256 / P-256 or Ed25519) in-memory or secure hardware using Web Crypto API (`subtle.generateKey` with `extractable: false`).
- Engineers MUST NOT persist private keys in `localStorage`, `sessionStorage`, or unencrypted files; keys must remain in memory or platform-native secure enclaves.
- Code MUST include the 'ath' (access token hash) claim in the DPoP proof whenever the request presents an access token, computed as base64url(sha256(accessToken)).
- Services MUST canonicalize the 'htu' claim to include only the protocol, host, and pathname, explicitly stripping query strings, fragments, and userinfo.
- Components NEVER reuse DPoP proofs across multiple requests; every request must generate a fresh proof with a unique 'jti' (UUIDv4) and accurate 'iat' timestamp.
- Engineers MUST implement automated retry handling for HTTP 401 responses containing a `use_dpop_nonce` error code, updating the cached server nonce and re-signing the request.

## Bad vs Good Implementations
### RFC 9449 Compliant DPoP Proof Generator & Fetch Interceptor

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Transmitting raw Bearer tokens without cryptographic binding allows malicious interceptors, compromised dependencies, or XSS vectors to exfiltrate and replay the token anywhere without possession of client secrets.
```typescript
import axios from 'axios';

// ANTI-PATTERN: Using raw Bearer tokens vulnerable to token theft/exfiltration
export async function callProtectedApi(url: string, token: string) {
  const response = await fetch(url, {
    method: 'GET',
    headers: {
      // Flaw: Stolen bearer token can be replayed by any attacker from any IP
      'Authorization': `Bearer ${token}`,
    },
  });
  return response.json();
}
```

#### Production Standard (Correct)
> **Standard**: Adheres strictly to RFC 9449: generates a non-extractable P-256 ECDSA key, embeds minimal public JWK in the header, canonicalizes HTU without queries, generates fresh JTI per request, includes the 'ath' claim for access tokens, binds authorization with 'DPoP <token>', and transparently handles the DPoP-Nonce challenge retry loop.
```typescript
import { base64UrlEncode } from './cryptoUtils';

interface DPoPKeyPair {
  privateKey: CryptoKey;
  publicKeyJwk: JsonWebKey;
}

let cachedKeyPair: DPoPKeyPair | null = null;
let currentNonce: string | null = null;

export async function getOrCreateDPoPKeyPair(): Promise<DPoPKeyPair> {
  if (!cachedKeyPair) {
    const keyPair = await crypto.subtle.generateKey(
      { name: 'ECDSA', namedCurve: 'P-256' },
      false, // Invariant: Non-extractable private key
      ['sign']
    );
    const rawPublicJwk = await crypto.subtle.exportKey('jwk', keyPair.publicKey);
    const publicKeyJwk = {
      kty: rawPublicJwk.kty,
      crv: rawPublicJwk.crv,
      x: rawPublicJwk.x,
      y: rawPublicJwk.y,
    };
    cachedKeyPair = { privateKey: keyPair.privateKey, publicKeyJwk };
  }
  return cachedKeyPair;
}

async function computeAccessTokenHash(token: string): Promise<string> {
  const buffer = new TextEncoder().encode(token);
  const hashBuffer = await crypto.subtle.digest('SHA-256', buffer);
  return base64UrlEncode(new Uint8Array(hashBuffer));
}

export async function createDPoPProof(
  method: string,
  url: string,
  accessToken?: string
): Promise<string> {
  const { privateKey, publicKeyJwk } = await getOrCreateDPoPKeyPair();
  const parsedUrl = new URL(url);
  const canonicalHtu = `${parsedUrl.origin}${parsedUrl.pathname}`;

  const header = {
    typ: 'dpop+jwt',
    alg: 'ES256',
    jwk: publicKeyJwk,
  };

  const payload: Record<string, unknown> = {
    jti: crypto.randomUUID(),
    htm: method.toUpperCase(),
    htu: canonicalHtu,
    iat: Math.floor(Date.now() / 1000),
  };

  if (currentNonce) {
    payload.nonce = currentNonce;
  }
  if (accessToken) {
    payload.ath = await computeAccessTokenHash(accessToken);
  }

  const encodedHeader = base64UrlEncode(new TextEncoder().encode(JSON.stringify(header)));
  const encodedPayload = base64UrlEncode(new TextEncoder().encode(JSON.stringify(payload)));
  const signingInput = `${encodedHeader}.${encodedPayload}`;

  const signature = await crypto.subtle.sign(
    { name: 'ECDSA', hash: 'SHA-256' },
    privateKey,
    new TextEncoder().encode(signingInput)
  );

  return `${signingInput}.${base64UrlEncode(new Uint8Array(signature))}`;
}

export async function secureDPoPFetch(
  url: string,
  init: RequestInit = {},
  accessToken?: string
): Promise<Response> {
  const method = (init.method || 'GET').toUpperCase();
  let dpopProof = await createDPoPProof(method, url, accessToken);

  const headers = new Headers(init.headers || {});
  headers.set('DPoP', dpopProof);
  if (accessToken) {
    headers.set('Authorization', `DPoP ${accessToken}`);
  }

  let response = await fetch(url, { ...init, method, headers });

  const newNonce = response.headers.get('DPoP-Nonce');
  if (newNonce) {
    currentNonce = newNonce;
  }

  // Handle RFC 9449 Section 4.3 server nonce challenge rotation
  if (response.status === 401 && response.headers.get('WWW-Authenticate')?.includes('error="use_dpop_nonce"')) {
    dpopProof = await createDPoPProof(method, url, accessToken);
    headers.set('DPoP', dpopProof);
    response = await fetch(url, { ...init, method, headers });
  }

  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: OAuth 2.0 RFC 9449 DPoP Ephemeral Cryptographic Binding

OAuth 2.0 RFC 9449 DPoP Ephemeral Cryptographic Binding defines an industrial-grade behavioral standard for security engineering. Enforces RFC 9449 Demonstrating Proof-of-Possession (DPoP) at application boundaries to bind OAuth access and refresh tokens to non-extractable client key pairs. Prevents token replay and unauthorized credential reuse by requiring signed ephemeral proof JWTs with strict HTTP method, URI normalization, token hash ('ath'), and server nonce verification on every request. Replaces traditional bearer authentication with sender-constrained token validation across all client-server communications. 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: Transmitting Unbound Bearer Tokens or Reusing Static DPoP Proofs Without Nonce and ATH Validation 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 DriftTransmitting Unbound Bearer Tokens or Reusing Static DPoP Proofs Without Nonce and ATH ValidationCritical
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 generate non-extractable asymmetric key pairs (ES256 / P-256 or Ed25519) in-memory or secure hardware using Web Crypto API (`subtle.generateKey` with `extractable

Engineers MUST ALWAYS generate non-extractable asymmetric key pairs (ES256 / P-256 or Ed25519) in-memory or secure hardware using Web Crypto API (`subtle.generateKey` with `extractable: 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 persist private keys in `localStorage`, `sessionStorage`, or unencrypted files

Engineers MUST NOT persist private keys in `localStorage`, `sessionStorage`, or unencrypted files; keys must remain in memory or platform-native secure enclaves.

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 MUST include the 'ath' (access token hash) claim in the DPoP proof whenever the request presents an access token, computed as base64url(sha256(accessToken)).

Code MUST include the 'ath' (access token hash) claim in the DPoP proof whenever the request presents an access token, computed as base64url(sha256(accessToken)).

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

Services MUST canonicalize the 'htu' claim to include only the protocol, host, and pathname, explicitly stripping query strings, fragments, and userinfo.

Services MUST canonicalize the 'htu' claim to include only the protocol, host, and pathname, explicitly stripping query strings, fragments, and userinfo.

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

Components NEVER reuse DPoP proofs across multiple requests

Components NEVER reuse DPoP proofs across multiple requests; every request must generate a fresh proof with a unique 'jti' (UUIDv4) and accurate 'iat' timestamp.

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

Engineers MUST implement automated retry handling for HTTP 401 responses containing a `use_dpop_nonce` error code, updating the cached server nonce and re-signing the request.

Engineers MUST implement automated retry handling for HTTP 401 responses containing a `use_dpop_nonce` error code, updating the cached server nonce and re-signing the request.

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 OAuth 2.0 RFC 9449 DPoP Ephemeral Cryptographic Binding critical for AI coding assistants?

Enforces RFC 9449 Demonstrating Proof-of-Possession (DPoP) at application boundaries to bind OAuth access and refresh tokens to non-extractable client key pairs. Prevents token replay and unauthorized credential reuse by requiring signed ephemeral proof JWTs with strict HTTP method, URI normalization, token hash ('ath'), and server nonce verification on every request. Replaces traditional bearer authentication with sender-constrained token validation across all client-server communications. 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 (Transmitting Unbound Bearer Tokens or Reusing Static DPoP Proofs Without Nonce and ATH Validation) 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

OAuth