This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: oauth-2-1-dpop-token-binding-nonce-rotation-standard

OAuth 2.1 RFC 9449 DPoP Token Binding and Replay-Resistant Nonce Rotation

Enforces strict RFC 9449 Demonstrating Proof-of-Possession (DPoP) at the application and transport layers. Mandates cryptographic binding of access and refresh tokens to ephemeral client-side private keys via thumbprint (jkt) and access token hash (ath) verification. Guarantees zero-trust replay resistance by enforcing server-directed DPoP-Nonce rotation and eliminating fallback to bearer authorization.

Prohibited Anti-Pattern: Unbound Bearer Token Exfiltration and Replayable Static DPoP Proofs

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OAuth 2.1 RFC 9449 DPoP Token Binding and Replay-Resistant Nonce Rotation - Enforces strict RFC 9449 Demonstrating Proof-of-Possession (DPoP) at the application and transport layers. Mandates cryptographic binding of access and refresh tokens to ephemeral client-side private keys via thumbprint (jkt) and access token hash (ath) verification. Guarantees zero-trust replay resistance by enforcing server-directed DPoP-Nonce rotation and eliminating fallback to bearer authorization.
globs: src/auth/**/*.{ts,tsx}, src/api/**/*.{ts,tsx}, src/lib/http/**/*.{ts,tsx}, src/middleware/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/oauth-2-1-dpop-token-binding-nonce-rotation-standard"
---

# OAuth 2.1 RFC 9449 DPoP Token Binding and Replay-Resistant Nonce Rotation

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbound Bearer Token Exfiltration and Replayable Static DPoP Proofs

## System Constraints
You are a Principal Security Architect enforcing OAuth 2.1 DPoP (RFC 9449) and replay-resistant nonce rotation across all client and API boundaries. You must strictly prevent plain Bearer token usage, ensure cryptographic binding of tokens via WebCrypto asymmetric key pairs, require exact HTTP method ('htm') and URI ('htu') normalizations in DPoP proofs, and implement zero-fallback, single-retry DPoP-Nonce handshake mechanics.

## Strict Guidelines
- Engineers MUST ALWAYS generate ephemeral, non-exportable asymmetric key pairs (e.g., ECDSA P-256 or Ed25519) within the secure client enclave (WebCrypto SubtleCrypto) for DPoP proof generation.
- Engineers MUST NEVER fallback to raw 'Bearer' Authorization headers when interacting with endpoints protected by or negotiating DPoP; headers MUST use the 'DPoP <token>' scheme.
- Code MUST compute and include the 'ath' (Access Token Hash) claim in DPoP proofs when accessing protected resources, formatted as base64url-encoded SHA-256 of the ASCII access token.
- Code MUST validate and normalize the 'htm' (HTTP Method) and 'htu' (HTTP URI without query or fragment) claims in every generated and verified DPoP proof.
- Services MUST enforce server-issued 'DPoP-Nonce' validation with strict expiry and single-use cache tracking; clients MUST capture 'DPoP-Nonce' headers on 401/400 responses and retry exactly once with updated nonces.
- Components NEVER store private signing keys in localStorage, cookies, or accessible serialized memory; keys must remain non-extractable in CryptoKeyPair handles.

## Bad vs Good Implementations
### DPoP Client Fetch Wrapper with Nonce Rotation and 'ath' Binding

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Transmits tokens via standard Bearer scheme without cryptographic proof-of-possession. An adversary intercepting the token through an XSS, CDN proxy, or TLS termination layer can replay it without restriction. There is no proof bound to the HTTP method or URL.
```typescript
import axios from 'axios';

// VULNERABLE: Employs bearer tokens vulnerable to token theft/replay,
// lacks ephemeral key binding, and fails to handle RFC 9449 DPoP nonce challenge
export async function callProtectedApi(url: string, method: string, accessToken: string) {
  return axios({
    url,
    method,
    headers: {
      Authorization: `Bearer ${accessToken}`,
    },
  });
}
```

#### Production Standard (Correct)
> **Standard**: Implements RFC 9449 compliance using ES256 key pair binding. Generates a 'dpop+jwt' proof containing normalized 'htm', 'htu', and base64url-encoded 'ath' token hash. Gracefully handles 401 DPoP-Nonce challenges with an atomic single retry, precluding token exfiltration and replay attacks.
```typescript
import { exportJWK, SignJWT } from 'jose';

interface DPoPClientState {
  keyPair: CryptoKeyPair;
  lastNonce?: string;
}

async function createDPoPProof(
  keyPair: CryptoKeyPair,
  httpMethod: string,
  httpUrl: string,
  accessToken?: string,
  nonce?: string
): Promise<string> {
  const cleanUrl = new URL(httpUrl);
  cleanUrl.search = '';
  cleanUrl.hash = '';

  const publicJwk = await exportJWK(keyPair.publicKey);
  delete publicJwk.ext;
  delete publicJwk.key_ops;

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

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

  return jwt.sign(keyPair.privateKey);
}

export async function secureDPoPFetch(
  state: DPoPClientState,
  url: string,
  options: RequestInit = {},
  accessToken?: string
): Promise<Response> {
  const method = options.method || 'GET';
  const initialProof = await createDPoPProof(state.keyPair, method, url, accessToken, state.lastNonce);

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

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

  const returnedNonce = response.headers.get('DPoP-Nonce');
  if (returnedNonce) {
    state.lastNonce = returnedNonce;
  }

  // Handle server-demanded nonce rotation (RFC 9449 Section 4.3 / 8.2)
  if (response.status === 401 && returnedNonce && !headers.get('X-DPoP-Retried')) {
    const retryProof = await createDPoPProof(state.keyPair, method, url, accessToken, returnedNonce);
    const retryHeaders = new Headers(options.headers);
    retryHeaders.set('DPoP', retryProof);
    retryHeaders.set('X-DPoP-Retried', '1');
    if (accessToken) {
      retryHeaders.set('Authorization', `DPoP ${accessToken}`);
    }
    response = await fetch(url, { ...options, headers: retryHeaders });
  }

  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.1 RFC 9449 DPoP Token Binding and Replay-Resistant Nonce Rotation

OAuth 2.1 RFC 9449 DPoP Token Binding and Replay-Resistant Nonce Rotation defines an industrial-grade behavioral standard for security engineering. Enforces strict RFC 9449 Demonstrating Proof-of-Possession (DPoP) at the application and transport layers. Mandates cryptographic binding of access and refresh tokens to ephemeral client-side private keys via thumbprint (jkt) and access token hash (ath) verification. Guarantees zero-trust replay resistance by enforcing server-directed DPoP-Nonce rotation and eliminating fallback to bearer authorization. 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 Token Exfiltration and Replayable Static DPoP Proofs 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 Token Exfiltration and Replayable Static DPoP ProofsCritical
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 ephemeral, non-exportable asymmetric key pairs (e.g., ECDSA P-256 or Ed25519) within the secure client enclave (WebCrypto SubtleCrypto) for DPoP proof generation.

Engineers MUST ALWAYS generate ephemeral, non-exportable asymmetric key pairs (e.g., ECDSA P-256 or Ed25519) within the secure client enclave (WebCrypto SubtleCrypto) for DPoP proof generation.

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 NEVER fallback to raw 'Bearer' Authorization headers when interacting with endpoints protected by or negotiating DPoP

Engineers MUST NEVER fallback to raw 'Bearer' Authorization headers when interacting with endpoints protected by or negotiating DPoP; headers MUST use the 'DPoP <token>' scheme.

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 compute and include the 'ath' (Access Token Hash) claim in DPoP proofs when accessing protected resources, formatted as base64url-encoded SHA-256 of the ASCII access token.

Code MUST compute and include the 'ath' (Access Token Hash) claim in DPoP proofs when accessing protected resources, formatted as base64url-encoded SHA-256 of the ASCII access token.

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 validate and normalize the 'htm' (HTTP Method) and 'htu' (HTTP URI without query or fragment) claims in every generated and verified DPoP proof.

Code MUST validate and normalize the 'htm' (HTTP Method) and 'htu' (HTTP URI without query or fragment) claims in every generated and verified DPoP proof.

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 enforce server-issued 'DPoP-Nonce' validation with strict expiry and single-use cache tracking

Services MUST enforce server-issued 'DPoP-Nonce' validation with strict expiry and single-use cache tracking; clients MUST capture 'DPoP-Nonce' headers on 401/400 responses and retry exactly once with updated nonces.

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 private signing keys in localStorage, cookies, or accessible serialized memory

Components NEVER store private signing keys in localStorage, cookies, or accessible serialized memory; keys must remain non-extractable in CryptoKeyPair handles.

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.1 RFC 9449 DPoP Token Binding and Replay-Resistant Nonce Rotation critical for AI coding assistants?

Enforces strict RFC 9449 Demonstrating Proof-of-Possession (DPoP) at the application and transport layers. Mandates cryptographic binding of access and refresh tokens to ephemeral client-side private keys via thumbprint (jkt) and access token hash (ath) verification. Guarantees zero-trust replay resistance by enforcing server-directed DPoP-Nonce rotation and eliminating fallback to bearer authorization. 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 Token Exfiltration and Replayable Static DPoP Proofs) 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