This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: oauth2-dpop-rfc9449-proof-nonce-enforcement

OAuth 2.0 DPoP (RFC 9449) Cryptographic Proof & Nonce Rotation Enforcement

Mandates client-side asymmetric key-binding for all egress token and resource server requests in accordance with RFC 9449 (DPoP). Enforces strict single-use JTI proof generation, URI/method canonicalization, public-only JWK header exposure, and automatic RFC 9449 Section 4.3 DPoP-Nonce challenge retries to neutralize token theft and replay attacks.

Prohibited Anti-Pattern: Statically Reusing Expired DPoP Proofs or Dropping Server DPoP-Nonce 401 Challenge Synchronization

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OAuth 2.0 DPoP (RFC 9449) Cryptographic Proof & Nonce Rotation Enforcement - Mandates client-side asymmetric key-binding for all egress token and resource server requests in accordance with RFC 9449 (DPoP). Enforces strict single-use JTI proof generation, URI/method canonicalization, public-only JWK header exposure, and automatic RFC 9449 Section 4.3 DPoP-Nonce challenge retries to neutralize token theft and replay attacks.
globs: src/auth/**/*.{ts,tsx,js,jsx}, src/api/**/*.{ts,tsx,js,jsx}, src/http/**/*.{ts,tsx,js,jsx}, src/services/**/*.{ts,tsx,js,jsx}, src/lib/auth/**/*.{ts,tsx,js,jsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/oauth2-dpop-rfc9449-proof-nonce-enforcement"
---

# OAuth 2.0 DPoP (RFC 9449) Cryptographic Proof & Nonce Rotation Enforcement

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Statically Reusing Expired DPoP Proofs or Dropping Server DPoP-Nonce 401 Challenge Synchronization

## System Constraints
You are a Principal Security Architect enforcing OAuth 2.0 Demonstrating Proof of Possession (DPoP, RFC 9449). Ensure every outbound HTTP request to token endpoints and protected resource servers cryptographically binds the request using an ephemeral, client-held asymmetric key pair. Mandate dynamic jti generation, method/URI validation, automatic server-nonce state management, and bounded retry loops on 401 'use_dpop_nonce' challenges.

## Strict Guidelines
- Engineers MUST ALWAYS compute DPoP proof JWT headers with 'typ': 'dpop+jwt' and an embedded public-only 'jwk' (never including private components such as 'd').
- Engineers MUST ALWAYS generate a fresh cryptographically random 'jti' (UUIDv4 or 128-bit CSPRNG hex) and current 'iat' timestamp for every distinct outbound request to prevent replay.
- Engineers MUST ALWAYS bind the 'htm' (HTTP method) and 'htu' (canonical HTTP URI string without query string or fragment) claims to the targeted request.
- Engineers MUST compute and attach the 'ath' (SHA-256 base64url-encoded hash of the Access Token) claim when calling protected resource servers with an access token.
- Services MUST capture the 'DPoP-Nonce' HTTP header from any server response and persist it in a scoped, per-origin memory store for subsequent proof generation.
- Clients MUST automatically intercept HTTP 401 responses with WWW-Authenticate header containing error='use_dpop_nonce', update the origin's cached nonce, regenerate the proof, and retry the request exactly once.
- Components NEVER persist the asymmetric private key to unencrypted browser storage (localStorage/sessionStorage); keys MUST be kept in non-extractable Web Crypto CryptoKey objects or secure runtime vaults.

## Bad vs Good Implementations
### Naive Token Attachment vs. RFC 9449 DPoP Client Interceptor with Nonce Handling

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Transmits standard bearer tokens without cryptographic proof-of-possession, or attempts DPoP using a static, pre-generated JWT. It omits the access token hash ('ath'), ignores dynamic 'htu'/'htm' binding, and fails to handle the required RFC 9449 401 'use_dpop_nonce' server challenge.
```typescript
import axios from 'axios';

// ANTI-PATTERN: Plain Bearer token transmission vulnerable to interception and replay.
// Static proof generation that ignores server nonce rotation and lacks cryptographic binding.
export async function fetchProtectedResource(url: string, token: string) {
  return axios.get(url, {
    headers: {
      Authorization: `Bearer ${token}`,
      // Insecure: Missing DPoP proof or reusing static DPoP header without dynamic jti/nonce
      DPoP: 'eyJhbGciOiJFUzI1NiIsInR5cCI6ImRwb3Arand0In0...static_reused_proof'
    }
  });
}
```

#### Production Standard (Correct)
> **Standard**: Implements full RFC 9449 compliance: signs each request with an ephemeral 'jti', canonicalizes 'htu' and 'htm', includes the SHA-256 'ath' hash of the access token, exports only public JWK parameters, records 'DPoP-Nonce' headers, and safely executes a single retry upon receiving a 'use_dpop_nonce' challenge.
```typescript
import { SignJWT, exportJWK, type CryptoKeyPair } from 'jose';

interface DPoPClientState {
  keyPair: CryptoKeyPair;
  nonces: Map<string, string>; // Maps target origin to active DPoP-Nonce
}

async function createDPoPProof(
  state: DPoPClientState,
  method: string,
  url: string,
  accessToken?: string
): Promise<string> {
  const parsedUrl = new URL(url);
  const origin = parsedUrl.origin;
  const htu = `${parsedUrl.origin}${parsedUrl.pathname}`;
  const publicJwk = await exportJWK(state.keyPair.publicKey);
  
  // Remove keyops/ext to avoid leaking key internal flags; ensure public only
  delete publicJwk.d;

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

  if (accessToken) {
    const hashBuffer = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(accessToken));
    const ath = Buffer.from(hashBuffer).toString('base64url');
    builder = builder.setSubject(ath); // 'ath' claim
  }

  const activeNonce = state.nonces.get(origin);
  if (activeNonce) {
    builder = builder.setClaim('nonce', activeNonce);
  }

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

export async function dpopFetch(
  state: DPoPClientState,
  input: string,
  init: RequestInit = {},
  accessToken?: string,
  isRetry = false
): Promise<Response> {
  const url = new URL(input, window.location.origin).toString();
  const method = init.method || 'GET';
  
  const proof = await createDPoPProof(state, method, url, accessToken);
  const headers = new Headers(init.headers);
  headers.set('DPoP', proof);
  if (accessToken) {
    headers.set('Authorization', `DPoP ${accessToken}`);
  }

  const response = await fetch(url, { ...init, method, headers });
  const origin = new URL(url).origin;
  
  // Capture new server nonce if rotated in response
  const serverNonce = response.headers.get('DPoP-Nonce');
  if (serverNonce) {
    state.nonces.set(origin, serverNonce);
  }

  // Handle RFC 9449 Section 4.3 Nonce Challenge
  if (response.status === 401 && !isRetry) {
    const authHeader = response.headers.get('WWW-Authenticate') || '';
    if (authHeader.includes('error="use_dpop_nonce"') && serverNonce) {
      return dpopFetch(state, input, init, accessToken, true);
    }
  }

  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 DPoP (RFC 9449) Cryptographic Proof & Nonce Rotation Enforcement

OAuth 2.0 DPoP (RFC 9449) Cryptographic Proof & Nonce Rotation Enforcement defines an industrial-grade behavioral standard for security engineering. Mandates client-side asymmetric key-binding for all egress token and resource server requests in accordance with RFC 9449 (DPoP). Enforces strict single-use JTI proof generation, URI/method canonicalization, public-only JWK header exposure, and automatic RFC 9449 Section 4.3 DPoP-Nonce challenge retries to neutralize token theft and replay attacks. 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: Statically Reusing Expired DPoP Proofs or Dropping Server DPoP-Nonce 401 Challenge Synchronization 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 DriftStatically Reusing Expired DPoP Proofs or Dropping Server DPoP-Nonce 401 Challenge SynchronizationCritical
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 compute DPoP proof JWT headers with 'typ'

Engineers MUST ALWAYS compute DPoP proof JWT headers with 'typ': 'dpop+jwt' and an embedded public-only 'jwk' (never including private components such as 'd').

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 ALWAYS generate a fresh cryptographically random 'jti' (UUIDv4 or 128-bit CSPRNG hex) and current 'iat' timestamp for every distinct outbound request to prevent replay.

Engineers MUST ALWAYS generate a fresh cryptographically random 'jti' (UUIDv4 or 128-bit CSPRNG hex) and current 'iat' timestamp for every distinct outbound request to prevent replay.

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

Engineers MUST ALWAYS bind the 'htm' (HTTP method) and 'htu' (canonical HTTP URI string without query string or fragment) claims to the targeted request.

Engineers MUST ALWAYS bind the 'htm' (HTTP method) and 'htu' (canonical HTTP URI string without query string or fragment) claims to the targeted 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.
4

Engineers MUST compute and attach the 'ath' (SHA-256 base64url-encoded hash of the Access Token) claim when calling protected resource servers with an access token.

Engineers MUST compute and attach the 'ath' (SHA-256 base64url-encoded hash of the Access Token) claim when calling protected resource servers with an 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.
5

Services MUST capture the 'DPoP-Nonce' HTTP header from any server response and persist it in a scoped, per-origin memory store for subsequent proof generation.

Services MUST capture the 'DPoP-Nonce' HTTP header from any server response and persist it in a scoped, per-origin memory store for subsequent 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.
6

Clients MUST automatically intercept HTTP 401 responses with WWW-Authenticate header containing error='use_dpop_nonce', update the origin's cached nonce, regenerate the proof, and retry the request exactly once.

Clients MUST automatically intercept HTTP 401 responses with WWW-Authenticate header containing error='use_dpop_nonce', update the origin's cached nonce, regenerate the proof, and retry the request exactly once.

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.
7

Components NEVER persist the asymmetric private key to unencrypted browser storage (localStorage/sessionStorage)

Components NEVER persist the asymmetric private key to unencrypted browser storage (localStorage/sessionStorage); keys MUST be kept in non-extractable Web Crypto CryptoKey objects or secure runtime vaults.

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 DPoP (RFC 9449) Cryptographic Proof & Nonce Rotation Enforcement critical for AI coding assistants?

Mandates client-side asymmetric key-binding for all egress token and resource server requests in accordance with RFC 9449 (DPoP). Enforces strict single-use JTI proof generation, URI/method canonicalization, public-only JWK header exposure, and automatic RFC 9449 Section 4.3 DPoP-Nonce challenge retries to neutralize token theft and replay attacks. 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 (Statically Reusing Expired DPoP Proofs or Dropping Server DPoP-Nonce 401 Challenge Synchronization) 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