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

OAuth 2.1 RFC 9449 DPoP Sender-Constrained Ephemeral Key Attestation Guardrail

Enforces strict sender-constrained token validation via Demonstrating Proof-of-Possession (RFC 9449) across all authenticated network boundaries. Every outbound request to protected resources must generate and attach a cryptographically bound, ephemeral asymmetric proof-of-possession JWT matching the exact HTTP method, canonicalized URI, access token hash (ath), and server-issued nonce. Prevents bearer token exfiltration, token reuse attacks, and session hijacking by invalidating captured access tokens without possession of the non-extractable client private key.

Prohibited Anti-Pattern: Transmitting Unconstrained Bearer Tokens or Emitting Malformed DPoP Proofs with Reused Nonces and Non-Canonical URIs

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OAuth 2.1 RFC 9449 DPoP Sender-Constrained Ephemeral Key Attestation Guardrail - Enforces strict sender-constrained token validation via Demonstrating Proof-of-Possession (RFC 9449) across all authenticated network boundaries. Every outbound request to protected resources must generate and attach a cryptographically bound, ephemeral asymmetric proof-of-possession JWT matching the exact HTTP method, canonicalized URI, access token hash (ath), and server-issued nonce. Prevents bearer token exfiltration, token reuse attacks, and session hijacking by invalidating captured access tokens without possession of the non-extractable client private key.
globs: src/auth/**/*.{ts,tsx}, src/api/**/*.{ts,tsx}, src/lib/http/**/*.{ts,tsx}, src/services/**/*.{ts,tsx}, src/middleware/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/oauth2-dpop-rfc9449-sender-constrained-attestation"
---

# OAuth 2.1 RFC 9449 DPoP Sender-Constrained Ephemeral Key Attestation Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Transmitting Unconstrained Bearer Tokens or Emitting Malformed DPoP Proofs with Reused Nonces and Non-Canonical URIs

## System Constraints
You are a Principal Security Architect enforcing OAuth 2.1 RFC 9449 (Demonstrating Proof-of-Possession at the Application Layer). You must forbid standard Bearer tokens on sensitive pathways and enforce cryptographic sender-constraining via ephemeral Web Crypto keys. Ensure that DPoP proof generation incorporates canonical HTTP method (htm), normalized target URI (htu), unique JWT ID (jti), access token hash (ath), issued-at timestamp (iat), and server nonces, with automatic nonce synchronization on 401 challenges.

## Strict Guidelines
- Engineers MUST ALWAYS generate asymmetric key pairs (ECDSA P-256/ES256 or Ed25519) marked as 'extractable: false' for private keys using Web Crypto API (SubtleCrypto).
- Engineers MUST NOT persist private DPoP signing keys in local storage, session storage, or unencrypted cookies; keys must reside exclusively in ephemeral client memory or hardware-backed stores.
- Code MUST calculate the 'ath' claim (SHA-256 digest of the access token, base64url-encoded without padding) and embed it inside the DPoP payload when accessing protected resources.
- Services MUST canonicalize the 'htu' claim per RFC 9449 Section 4.2 by stripping query strings, fragments, userinfo, and normalizing scheme and host to lowercase.
- Components NEVER reissue a DPoP proof with duplicate 'jti' identifiers or outdated 'iat' timestamps; each HTTP request must execute a fresh cryptographic signing operation.
- HTTP clients MUST intercept 'use_dpop_nonce' server errors (HTTP 401 with DPoP-Nonce header), cache the new nonce securely, and replay the request at most once to prevent infinite invocation loops.

## Bad vs Good Implementations
### Naive Bearer Token Dispatch vs. RFC 9449 Compliant DPoP Proof Attestation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Transmits a bare token without cryptographic sender-constraining. If intercepted via proxy logs, MITM, XSS, or memory scraping, an attacker can replay this token across different endpoints without possessing any client secrets.
```typescript
import axios from 'axios';

// ANTI-PATTERN: Raw bearer token vulnerable to exfiltration and replay attacks.
export async function fetchSensitiveProfile(accessToken: string, endpoint: string) {
  const response = await axios.get(endpoint, {
    headers: {
      // Bearer token has no cryptographic binding to the caller or request target
      Authorization: `Bearer ${accessToken}`,
    },
  });
  return response.data;
}
```

#### Production Standard (Correct)
> **Standard**: Adheres to RFC 9449: creates non-extractable P-256 keys, computes mandatory 'ath' hash of the access token, canonicalizes the target URI ('htu'), provides unique 'jti' identifiers, attaches the public JWK in the header, and handles DPoP-Nonce rotation challenges with controlled single-retry semantics.
```typescript
import { base64url } from 'jose';

interface DPoPKeyPair {
  publicKey: CryptoKey;
  privateKey: CryptoKey;
  publicJwk: JsonWebKey;
}

let cachedNonce: string | null = null;

// Invariant: Non-extractable ephemeral ECDSA P-256 key pair
export async function generateDPoPKeyPair(): Promise<DPoPKeyPair> {
  const keyPair = await crypto.subtle.generateKey(
    { name: 'ECDSA', namedCurve: 'P-256' },
    false, // Private key MUST NOT be extractable
    ['sign']
  );
  const publicJwk = await crypto.subtle.exportKey('jwk', keyPair.publicKey);
  delete publicJwk.key_ops;
  delete publicJwk.ext;
  return { publicKey: keyPair.publicKey, privateKey: keyPair.privateKey, publicJwk };
}

export async function computeAth(accessToken: string): Promise<string> {
  const data = new TextEncoder().encode(accessToken);
  const digest = await crypto.subtle.digest('SHA-256', data);
  return base64url.encode(new Uint8Array(digest));
}

export async function createDPoPProof(
  keyPair: DPoPKeyPair,
  method: string,
  url: string,
  accessToken?: string
): Promise<string> {
  const parsed = new URL(url);
  // Canonicalize HTU: strip query and fragment
  const htu = `${parsed.protocol}//${parsed.host}${parsed.pathname}`;
  
  const header = {
    typ: 'dpop+jwt',
    alg: 'ES256',
    jwk: keyPair.publicJwk,
  };
  
  const payload: Record<string, unknown> = {
    jti: crypto.randomUUID(),
    htm: method.toUpperCase(),
    htu,
    iat: Math.floor(Date.now() / 1000),
  };

  if (cachedNonce) {
    payload.nonce = cachedNonce;
  }
  if (accessToken) {
    payload.ath = await computeAth(accessToken);
  }

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

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

  return `${encodedHeader}.${encodedPayload}.${base64url.encode(new Uint8Array(signature))}`;
}

export async function fetchWithDPoP(
  endpoint: string,
  method: string,
  accessToken: string,
  keyPair: DPoPKeyPair,
  retryCount = 0
): Promise<Response> {
  const proof = await createDPoPProof(keyPair, method, endpoint, accessToken);

  const response = await fetch(endpoint, {
    method,
    headers: {
      Authorization: `DPoP ${accessToken}`,
      DPoP: proof,
    },
  });

  // Handle server-issued nonce challenge
  const serverNonce = response.headers.get('DPoP-Nonce');
  if (serverNonce) {
    cachedNonce = serverNonce;
  }

  if (response.status === 401 && serverNonce && retryCount === 0) {
    return fetchWithDPoP(endpoint, method, accessToken, keyPair, retryCount + 1);
  }

  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 Sender-Constrained Ephemeral Key Attestation Guardrail

OAuth 2.1 RFC 9449 DPoP Sender-Constrained Ephemeral Key Attestation Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces strict sender-constrained token validation via Demonstrating Proof-of-Possession (RFC 9449) across all authenticated network boundaries. Every outbound request to protected resources must generate and attach a cryptographically bound, ephemeral asymmetric proof-of-possession JWT matching the exact HTTP method, canonicalized URI, access token hash (ath), and server-issued nonce. Prevents bearer token exfiltration, token reuse attacks, and session hijacking by invalidating captured access tokens without possession of the non-extractable client private key. 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 Unconstrained Bearer Tokens or Emitting Malformed DPoP Proofs with Reused Nonces and Non-Canonical URIs 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 Unconstrained Bearer Tokens or Emitting Malformed DPoP Proofs with Reused Nonces and Non-Canonical URIsCritical
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 asymmetric key pairs (ECDSA P-256/ES256 or Ed25519) marked as 'extractable

Engineers MUST ALWAYS generate asymmetric key pairs (ECDSA P-256/ES256 or Ed25519) marked as 'extractable: false' for private keys using Web Crypto API (SubtleCrypto).

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 DPoP signing keys in local storage, session storage, or unencrypted cookies

Engineers MUST NOT persist private DPoP signing keys in local storage, session storage, or unencrypted cookies; keys must reside exclusively in ephemeral client memory or hardware-backed stores.

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 calculate the 'ath' claim (SHA-256 digest of the access token, base64url-encoded without padding) and embed it inside the DPoP payload when accessing protected resources.

Code MUST calculate the 'ath' claim (SHA-256 digest of the access token, base64url-encoded without padding) and embed it inside the DPoP payload when accessing protected resources.

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 per RFC 9449 Section 4.2 by stripping query strings, fragments, userinfo, and normalizing scheme and host to lowercase.

Services MUST canonicalize the 'htu' claim per RFC 9449 Section 4.2 by stripping query strings, fragments, userinfo, and normalizing scheme and host to lowercase.

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 reissue a DPoP proof with duplicate 'jti' identifiers or outdated 'iat' timestamps

Components NEVER reissue a DPoP proof with duplicate 'jti' identifiers or outdated 'iat' timestamps; each HTTP request must execute a fresh cryptographic signing operation.

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

HTTP clients MUST intercept 'use_dpop_nonce' server errors (HTTP 401 with DPoP-Nonce header), cache the new nonce securely, and replay the request at most once to prevent infinite invocation loops.

HTTP clients MUST intercept 'use_dpop_nonce' server errors (HTTP 401 with DPoP-Nonce header), cache the new nonce securely, and replay the request at most once to prevent infinite invocation loops.

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 Sender-Constrained Ephemeral Key Attestation Guardrail critical for AI coding assistants?

Enforces strict sender-constrained token validation via Demonstrating Proof-of-Possession (RFC 9449) across all authenticated network boundaries. Every outbound request to protected resources must generate and attach a cryptographically bound, ephemeral asymmetric proof-of-possession JWT matching the exact HTTP method, canonicalized URI, access token hash (ath), and server-issued nonce. Prevents bearer token exfiltration, token reuse attacks, and session hijacking by invalidating captured access tokens without possession of the non-extractable client private key. 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 Unconstrained Bearer Tokens or Emitting Malformed DPoP Proofs with Reused Nonces and Non-Canonical URIs) 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