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

OAuth 2.1 Demonstrating Proof-of-Possession (DPoP) Nonce Binding Standard

Enforces RFC 9449 Demonstrating Proof-of-Possession (DPoP) specifications across all edge API clients and token handlers. Mandates client-side generation of ephemeral asymmetric key-bound proof JWTs with strict server-issued nonce synchronization to neutralize bearer token exfiltration, replay attacks, and man-in-the-middle impersonation.

Prohibited Anti-Pattern: Transmitting Unbound Bearer Tokens or Static DPoP Proofs Without Dynamic Nonce Challenge Handshakes

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OAuth 2.1 Demonstrating Proof-of-Possession (DPoP) Nonce Binding Standard - Enforces RFC 9449 Demonstrating Proof-of-Possession (DPoP) specifications across all edge API clients and token handlers. Mandates client-side generation of ephemeral asymmetric key-bound proof JWTs with strict server-issued nonce synchronization to neutralize bearer token exfiltration, replay attacks, and man-in-the-middle impersonation.
globs: src/auth/**/*.{ts,tsx}, src/lib/api/**/*.{ts,tsx}, src/services/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-nonce-binding-standard"
---

# OAuth 2.1 Demonstrating Proof-of-Possession (DPoP) Nonce Binding Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Transmitting Unbound Bearer Tokens or Static DPoP Proofs Without Dynamic Nonce Challenge Handshakes

## System Constraints
You are a Principal Security Architect enforcing RFC 9449 OAuth 2.1 Demonstrating Proof-of-Possession (DPoP) standards. Reject all classical bearer tokens in edge-facing client interactions. Ensure all API requests sign a fresh, asymmetric DPoP proof bound to the HTTP method, targeted URI, an ephemeral server-issued nonce, and an access token hash (ath). When the resource server responds with a 401 error code containing 'use_dpop_nonce' and a fresh 'DPoP-Nonce' header, orchestrate an immediate single-pass retry using the updated nonce.

## Strict Guidelines
- Engineers MUST ALWAYS generate private/public key pairs (ECDSA P-256 or Ed25519) within non-exportable hardware-backed stores or isolated cryptographic contexts (e.g., SubtleCrypto with extractable=false).
- Engineers MUST ALWAYS sign DPoP proof JWTs with header claims 'typ': 'dpop+jwt' and the corresponding JWK public key embedded in 'jwk'.
- Engineers MUST NEVER include symmetric secrets in the DPoP header or persist private signing keys across non-isolated browser storage (e.g., localStorage, sessionStorage).
- Code MUST compute and include the 'ath' (Access Token Hash) claim in the DPoP proof whenever authenticating requests against protected resources using an access token.
- Services MUST capture 'DPoP-Nonce' headers returned by the server on 401 challenges or successful responses, store them per-target-origin, and inject them into subsequent proof claims.
- Components NEVER execute infinite loops on nonce handshakes; retry logic MUST limit nonce-refresh retries to exactly one attempt per outgoing HTTP request.

## Bad vs Good Implementations
### Naive Bearer Token Request vs. RFC 9449 Nonce-Aware DPoP Client

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Sending bare bearer tokens allows malicious actors who intercept the token (via XSS, CDN logging, or TLS termination) to replay the request from anywhere. It completely lacks proof-of-possession and replay protection.
```typescript
import axios from 'axios';

// ANTI-PATTERN: Traditional exfiltratable Bearer token usage
// Lacks cryptographic proof-of-possession, sender-constraining, and server nonce handshakes.
export async function callProtectedApi(url: string, accessToken: string): Promise<any> {
  const response = await fetch(url, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${accessToken}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ action: 'transfer_funds', amount: 500 })
  });

  if (!response.ok) {
    throw new Error(`API failed: ${response.status}`);
  }
  return response.json();
}
```

#### Production Standard (Correct)
> **Standard**: Cryptographically enforces RFC 9449 DPoP standards: initializes an unextractable ECDSA key pair, embeds the public JWK in the header, injects the access token hash (ath), htm, htu, and an ephemeral server-issued nonce. Automatically traps 401 challenges with 'use_dpop_nonce' to retry with the fresh nonce.
```typescript
import { importJWK, SignJWT, calculateJwkThumbprint } from 'jose';

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

let state: DPoPState | null = null;

async function getOrCreateKeyPair(): Promise<CryptoKeyPair> {
  if (!state) {
    const keyPair = await crypto.subtle.generateKey(
      { name: 'ECDSA', namedCurve: 'P-256' },
      false,
      ['sign', 'verify']
    );
    state = { keyPair };
  }
  return state.keyPair;
}

async function computeSha256Base64Url(data: string): Promise<string> {
  const buffer = new TextEncoder().encode(data);
  const hash = await crypto.subtle.digest('SHA-256', buffer);
  return btoa(String.fromCharCode(...new Uint8Array(hash)))
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=+$/, '');
}

async function generateDPoPProof(
  keyPair: CryptoKeyPair,
  httpMethod: string,
  httpUrl: string,
  accessToken?: string,
  nonce?: string
): Promise<string> {
  const publicJwk = await crypto.subtle.exportKey('jwk', keyPair.publicKey);
  const { d, ...cleanJwk } = publicJwk as JsonWebKey & { d?: string };

  const payload: Record<string, unknown> = {
    htm: httpMethod,
    htu: httpUrl.split('?')[0],
    jti: crypto.randomUUID()
  };

  if (nonce) payload.nonce = nonce;
  if (accessToken) payload.ath = await computeSha256Base64Url(accessToken);

  return new SignJWT(payload)
    .setProtectedHeader({ typ: 'dpop+jwt', alg: 'ES256', jwk: cleanJwk })
    .setIssuedAt()
    .sign(keyPair.privateKey);
}

export async function callProtectedApiDPoP(
  url: string,
  method: string,
  accessToken: string,
  payload?: unknown
): Promise<Response> {
  const keyPair = await getOrCreateKeyPair();
  
  const executeRequest = async (currentNonce?: string): Promise<Response> => {
    const dpopProof = await generateDPoPProof(keyPair, method, url, accessToken, currentNonce);
    return fetch(url, {
      method,
      headers: {
        'Authorization': `DPoP ${accessToken}`,
        'DPoP': dpopProof,
        'Content-Type': 'application/json'
      },
      body: payload ? JSON.stringify(payload) : undefined
    });
  };

  let response = await executeRequest(state?.cachedNonce);

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

  // RFC 9449 Nonce Challenge Handshake: Retry once with the server-supplied nonce
  if (response.status === 401 && response.headers.get('WWW-Authenticate')?.includes('use_dpop_nonce')) {
    if (!newNonce) {
      throw new Error('DPoP Nonce challenge issued without DPoP-Nonce response header.');
    }
    response = await executeRequest(newNonce);
  }

  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 Demonstrating Proof-of-Possession (DPoP) Nonce Binding Standard

OAuth 2.1 Demonstrating Proof-of-Possession (DPoP) Nonce Binding Standard defines an industrial-grade behavioral standard for security engineering. Enforces RFC 9449 Demonstrating Proof-of-Possession (DPoP) specifications across all edge API clients and token handlers. Mandates client-side generation of ephemeral asymmetric key-bound proof JWTs with strict server-issued nonce synchronization to neutralize bearer token exfiltration, replay attacks, and man-in-the-middle impersonation. 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 Static DPoP Proofs Without Dynamic Nonce Challenge Handshakes 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 Static DPoP Proofs Without Dynamic Nonce Challenge HandshakesCritical
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 private/public key pairs (ECDSA P-256 or Ed25519) within non-exportable hardware-backed stores or isolated cryptographic contexts (e.g., SubtleCrypto with extractable=false).

Engineers MUST ALWAYS generate private/public key pairs (ECDSA P-256 or Ed25519) within non-exportable hardware-backed stores or isolated cryptographic contexts (e.g., SubtleCrypto 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 ALWAYS sign DPoP proof JWTs with header claims 'typ'

Engineers MUST ALWAYS sign DPoP proof JWTs with header claims 'typ': 'dpop+jwt' and the corresponding JWK public key embedded in 'jwk'.

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 NEVER include symmetric secrets in the DPoP header or persist private signing keys across non-isolated browser storage (e.g., localStorage, sessionStorage).

Engineers MUST NEVER include symmetric secrets in the DPoP header or persist private signing keys across non-isolated browser storage (e.g., localStorage, sessionStorage).

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 include the 'ath' (Access Token Hash) claim in the DPoP proof whenever authenticating requests against protected resources using an access token.

Code MUST compute and include the 'ath' (Access Token Hash) claim in the DPoP proof whenever authenticating requests against protected resources using 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 'DPoP-Nonce' headers returned by the server on 401 challenges or successful responses, store them per-target-origin, and inject them into subsequent proof claims.

Services MUST capture 'DPoP-Nonce' headers returned by the server on 401 challenges or successful responses, store them per-target-origin, and inject them into subsequent proof claims.

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 execute infinite loops on nonce handshakes

Components NEVER execute infinite loops on nonce handshakes; retry logic MUST limit nonce-refresh retries to exactly one attempt per outgoing HTTP 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.1 Demonstrating Proof-of-Possession (DPoP) Nonce Binding Standard critical for AI coding assistants?

Enforces RFC 9449 Demonstrating Proof-of-Possession (DPoP) specifications across all edge API clients and token handlers. Mandates client-side generation of ephemeral asymmetric key-bound proof JWTs with strict server-issued nonce synchronization to neutralize bearer token exfiltration, replay attacks, and man-in-the-middle impersonation. 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 Static DPoP Proofs Without Dynamic Nonce Challenge Handshakes) 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