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

RFC 9449 Demonstrating Proof-of-Possession (DPoP) Invariant Enforcement

Enforces RFC 9449 Demonstrating Proof-of-Possession (DPoP) asymmetric key-binding invariants across OAuth 2.0 client requests and resource server validations. Mandates client-side ephemeral cryptographic key generation, strict non-exportable storage, exact HTTP request-bound proof generation (htm, htu, jti, ath), and server-side replay prevention with nonce coordination.

Prohibited Anti-Pattern: Bearer Token Fallback and Unbound In-Memory DPoP Proof Reuse

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: RFC 9449 Demonstrating Proof-of-Possession (DPoP) Invariant Enforcement - Enforces RFC 9449 Demonstrating Proof-of-Possession (DPoP) asymmetric key-binding invariants across OAuth 2.0 client requests and resource server validations. Mandates client-side ephemeral cryptographic key generation, strict non-exportable storage, exact HTTP request-bound proof generation (htm, htu, jti, ath), and server-side replay prevention with nonce coordination.
globs: src/**/auth/**/*.{ts,tsx}, src/**/middleware/**/*.{ts,tsx}, src/**/oauth/**/*.{ts,tsx}, src/**/api/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/rfc-9449-dpop-key-binding-standard"
---

# RFC 9449 Demonstrating Proof-of-Possession (DPoP) Invariant Enforcement

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Bearer Token Fallback and Unbound In-Memory DPoP Proof Reuse

## System Constraints
You are a Principal Security Architect enforcing the RFC 9449 DPoP Ephemeral Asymmetric Key-Binding Standard. Ensure all outbound OAuth 2.0 requests generate signed, non-reusable DPoP proof JWTs bound to an ephemeral asymmetric key pair (ES256 or Ed25519) stored in secure hardware or non-extractable CryptoKey primitives. Enforce that incoming resource server middleware strictly validates the DPoP proof's 'htm' (HTTP method), 'htu' (HTTP target URI normalized without query/fragment), 'jti' (unique token ID with cache-based replay checks), 'iat' (max 60s skew), and 'ath' (SHA-256 hash of the access token). Reject any fallbacks to standard Bearer tokens when DPoP is negotiated.

## Strict Guidelines
- Engineers MUST ALWAYS generate DPoP proof keypairs as non-extractable Web Crypto API CryptoKey instances using ECDSA P-256 ('ES256') or Ed25519.
- Engineers MUST NOT persist client private keys in browser localStorage, sessionStorage, or unencrypted cookies.
- Client requests MUST generate a unique 'jti' UUIDv4 for every outbound HTTP request and calculate the 'ath' (base64url-encoded SHA-256 hash) of the access token.
- Resource servers MUST strictly match 'htm' to request.method and 'htu' to the canonical target URL (excluding query strings and fragments).
- Services MUST reject DPoP proofs older than 60 seconds or with clock skew exceeding 5 seconds, and MUST record 'jti' values in a distributed TTL cache (e.g., Redis) to prevent replay.
- Services MUST respond with HTTP 401 and a 'DPoP-Nonce' header when a nonce is missing, expired, or invalid according to RFC 9449 Section 8.

## Bad vs Good Implementations
### Client-Side DPoP Proof Generation and Header Binding

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Transmitting DPoP proofs without dynamic 'jti', 'iat', and HTTP method/URI binding allows attackers to replay stolen proofs and tokens. Falling back to Bearer authorization violates RFC 9449 key-binding requirements.
```typescript
import axios from 'axios';

// ANTI-PATTERN: Sending access token as standard Bearer without proof of possession,
// or reusing a static pre-signed DPoP proof across multiple requests.
export async function callProtectedApi(url: string, token: string, staticProof: string) {
  return axios.get(url, {
    headers: {
      Authorization: `Bearer ${token}`,
      DPoP: staticProof // Replayed static proof: vulnerable to exfiltration
    }
  });
}
```

#### Production Standard (Correct)
> **Standard**: Creates a freshly minted, single-use DPoP proof for each outbound call. Binds the HTTP method ('htm'), canonical URI ('htu'), and access token hash ('ath') to the client's non-extractable private key, completely satisfying RFC 9449.
```typescript
import { SignJWT, calculateJwkThumbprint } from 'jose';

interface DPoPRequestOptions {
  url: string;
  method: string;
  accessToken: string;
  keyPair: CryptoKeyPair; // Non-extractable CryptoKeyPair
  serverNonce?: string;
}

export async function createDPoPProof({
  url,
  method,
  accessToken,
  keyPair,
  serverNonce
}: DPoPRequestOptions): Promise<string> {
  // Canonicalize URI: strip query and fragment per RFC 9449 Section 4.3.1
  const parsedUrl = new URL(url);
  const htu = `${parsedUrl.origin}${parsedUrl.pathname}`;
  
  // Calculate 'ath' (Access Token Hash)
  const tokenBuffer = new TextEncoder().encode(accessToken);
  const hashBuffer = await crypto.subtle.digest('SHA-256', tokenBuffer);
  const ath = Buffer.from(hashBuffer).toString('base64url');

  // Export public key as JWK (private key remains non-extractable)
  const publicJwk = await crypto.subtle.exportKey('jwk', keyPair.publicKey);

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

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

  return jwt.sign(keyPair.privateKey);
}

export async function callProtectedApi(
  url: string,
  method: string,
  accessToken: string,
  keyPair: CryptoKeyPair,
  nonce?: string
) {
  const dpopProof = await createDPoPProof({ url, method, accessToken, keyPair, serverNonce: nonce });

  return fetch(url, {
    method,
    headers: {
      Authorization: `DPoP ${accessToken}`,
      DPoP: dpopProof
    }
  });
}
```

### Server-Side RFC 9449 Proof Validation and Replay Protection

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Decodes the JWT without verifying the asymmetric signature against the header's embedded JWK, skips URI/method binding verification, fails to validate the access token hash ('ath'), and omits 'jti' replay cache checks.
```typescript
import { Request, Response, NextFunction } from 'express';
import { decodeJwt } from 'jose';

// ANTI-PATTERN: Decoding without signature verification, no htm/htu matching, no replay check
export function validateDPoP(req: Request, res: Response, next: NextFunction) {
  const dpopHeader = req.headers['dpop'] as string;
  if (!dpopHeader) return res.status(401).send('Missing DPoP');

  const payload = decodeJwt(dpopHeader);
  if (payload) {
    return next(); // Insecure: Signature unverified, jti not checked against cache
  }
  return res.status(401).send('Invalid DPoP');
}
```

#### Production Standard (Correct)
> **Standard**: Implements RFC 9449 Section 4.3 server verification: validates header 'typ', imports the ephemeral public JWK, checks maxTokenAge, confirms 'htm' and 'htu' canonical parity, checks 'ath' token binding, and enforces distributed 'jti' anti-replay caching.
```typescript
import { Request, Response, NextFunction } from 'express';
import { importJWK, jwtVerify, JWK } from 'jose';
import { createHash } from 'crypto';

interface ReplayCache {
  has(jti: string): Promise<boolean>;
  set(jti: string, ttlSeconds: number): Promise<void>;
}

export function createDPoPMiddleware(cache: ReplayCache) {
  return async (req: Request, res: Response, next: NextFunction) => {
    const authHeader = req.headers.authorization;
    const dpopHeader = req.headers['dpop'];

    if (!authHeader?.startsWith('DPoP ') || typeof dpopHeader !== 'string') {
      return res.status(401).json({ error: 'invalid_token', error_description: 'DPoP required' });
    }

    const accessToken = authHeader.slice(5).trim();

    try {
      // 1. Verify header typ and extract JWK
      const [rawHeader] = dpopHeader.split('.');
      const header = JSON.parse(Buffer.from(rawHeader, 'base64url').toString('utf8'));
      if (header.typ !== 'dpop+jwt' || !header.jwk) {
        return res.status(401).json({ error: 'invalid_dpop_proof' });
      }

      // 2. Verify signature with embedded public key
      const publicKey = await importJWK(header.jwk as JWK, header.alg);
      const { payload } = await jwtVerify(dpopHeader, publicKey, {
        algorithms: ['ES256', 'EdDSA'],
        maxTokenAge: '60s'
      });

      // 3. Validate htm and htu
      const canonicalUrl = `${req.protocol}://${req.get('host')}${req.baseUrl}${req.path}`;
      if (payload.htm !== req.method.toUpperCase() || payload.htu !== canonicalUrl) {
        return res.status(401).json({ error: 'invalid_dpop_proof', error_description: 'htm/htu mismatch' });
      }

      // 4. Validate ath (SHA-256 of access token)
      const expectedAth = createHash('sha256').update(accessToken).digest('base64url');
      if (payload.ath !== expectedAth) {
        return res.status(401).json({ error: 'invalid_dpop_proof', error_description: 'ath mismatch' });
      }

      // 5. Replay prevention via jti cache
      const jti = payload.jti as string;
      if (!jti || await cache.has(jti)) {
        return res.status(401).json({ error: 'invalid_dpop_proof', error_description: 'jti replayed' });
      }
      await cache.set(jti, 60);

      return next();
    } catch (err) {
      return res.status(401).json({ error: 'invalid_dpop_proof', error_description: (err as Error).message });
    }
  };
}
```

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 Demonstrating Proof-of-Possession (DPoP) Invariant Enforcement

RFC 9449 Demonstrating Proof-of-Possession (DPoP) Invariant Enforcement defines an industrial-grade behavioral standard for security engineering. Enforces RFC 9449 Demonstrating Proof-of-Possession (DPoP) asymmetric key-binding invariants across OAuth 2.0 client requests and resource server validations. Mandates client-side ephemeral cryptographic key generation, strict non-exportable storage, exact HTTP request-bound proof generation (htm, htu, jti, ath), and server-side replay prevention with nonce coordination. 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: Bearer Token Fallback and Unbound In-Memory DPoP Proof Reuse 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 DriftBearer Token Fallback and Unbound In-Memory DPoP Proof ReuseCritical
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 DPoP proof keypairs as non-extractable Web Crypto API CryptoKey instances using ECDSA P-256 ('ES256') or Ed25519.

Engineers MUST ALWAYS generate DPoP proof keypairs as non-extractable Web Crypto API CryptoKey instances using ECDSA P-256 ('ES256') or Ed25519.

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 client private keys in browser localStorage, sessionStorage, or unencrypted cookies.

Engineers MUST NOT persist client private keys in browser localStorage, sessionStorage, or unencrypted cookies.

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

Client requests MUST generate a unique 'jti' UUIDv4 for every outbound HTTP request and calculate the 'ath' (base64url-encoded SHA-256 hash) of the access token.

Client requests MUST generate a unique 'jti' UUIDv4 for every outbound HTTP request and calculate the 'ath' (base64url-encoded SHA-256 hash) of the 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

Resource servers MUST strictly match 'htm' to request.method and 'htu' to the canonical target URL (excluding query strings and fragments).

Resource servers MUST strictly match 'htm' to request.method and 'htu' to the canonical target URL (excluding query strings and fragments).

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 reject DPoP proofs older than 60 seconds or with clock skew exceeding 5 seconds, and MUST record 'jti' values in a distributed TTL cache (e.g., Redis) to prevent replay.

Services MUST reject DPoP proofs older than 60 seconds or with clock skew exceeding 5 seconds, and MUST record 'jti' values in a distributed TTL cache (e.g., Redis) 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.
6

Services MUST respond with HTTP 401 and a 'DPoP-Nonce' header when a nonce is missing, expired, or invalid according to RFC 9449 Section 8.

Services MUST respond with HTTP 401 and a 'DPoP-Nonce' header when a nonce is missing, expired, or invalid according to RFC 9449 Section 8.

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 Demonstrating Proof-of-Possession (DPoP) Invariant Enforcement critical for AI coding assistants?

Enforces RFC 9449 Demonstrating Proof-of-Possession (DPoP) asymmetric key-binding invariants across OAuth 2.0 client requests and resource server validations. Mandates client-side ephemeral cryptographic key generation, strict non-exportable storage, exact HTTP request-bound proof generation (htm, htu, jti, ath), and server-side replay prevention with nonce coordination. 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 (Bearer Token Fallback and Unbound In-Memory DPoP Proof Reuse) 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