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

OAuth 2.1 DPoP Ephemeral Asymmetric Key Binding Invariant

Enforces RFC 9449 Demonstrating Proof-of-Possession (DPoP) across all client authentication flows and distributed API gateway verifiers. Requires access and refresh tokens to be cryptographically bound to ephemeral client-generated asymmetric key pairs via JWK thumbprints (cnf.jkt), eliminating token exfiltration and replay attacks across untrusted network perimeters.

Prohibited Anti-Pattern: Replay-Vulnerable Bearer Tokens and Unverified DPoP Proof Headers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OAuth 2.1 DPoP Ephemeral Asymmetric Key Binding Invariant - Enforces RFC 9449 Demonstrating Proof-of-Possession (DPoP) across all client authentication flows and distributed API gateway verifiers. Requires access and refresh tokens to be cryptographically bound to ephemeral client-generated asymmetric key pairs via JWK thumbprints (cnf.jkt), eliminating token exfiltration and replay attacks across untrusted network perimeters.
globs: src/auth/**/*.{ts,tsx}, src/gateway/**/*.{ts,tsx}, src/middleware/**/*.{ts,tsx}, src/lib/http/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/oauth21-dpop-ephemeral-key-binding-guardrail"
---

# OAuth 2.1 DPoP Ephemeral Asymmetric Key Binding Invariant

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Replay-Vulnerable Bearer Tokens and Unverified DPoP Proof Headers

## System Constraints
You are a Principal Security Architect enforcing RFC 9449 OAuth 2.1 DPoP (Demonstrating Proof-of-Possession). You must reject any raw Bearer token transmissions, static shared secrets, extractable private keys, and missing or bypassed DPoP proof validations at edge gateways. Every token emission must be bound to a client-side ephemeral asymmetric key pair thumbprint, and every incoming API request must cryptographically verify proof-of-possession.

## Strict Guidelines
- Engineers MUST ALWAYS generate ephemeral, non-extractable asymmetric key pairs (ES256 / EdDSA) in memory or secure hardware enclave upon client initialization.
- Engineers MUST NOT persist private keys to localStorage, unencrypted sessionStorage, or distributed caches where unauthorized scripts or processes could access them.
- Services MUST validate the incoming 'DPoP' proof JWT by matching the 'htm' (HTTP method) and 'htu' (HTTP target URI excluding query/fragment) against the active request context.
- Distributed API Gateways MUST cryptographically verify that the SHA-256 thumbprint of the public key in the DPoP proof header matches the 'cnf.jkt' claim embedded within the sender-constrained access token.
- Components NEVER accept Bearer tokens on protected endpoints configured for DPoP; mismatched token types MUST trigger a 401 Unauthorized with 'WWW-Authenticate: DPoP error="invalid_dpop_proof"'.
- Services MUST reject DPoP proof JWTs older than acceptable clock skew (recommended 60 seconds) and MUST enforce single-use replay protection using distributed cache checks on the proof 'jti'.

## Bad vs Good Implementations
### API Gateway DPoP Proof and Token Thumbprint Verification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Accepts unbound Bearer tokens without DPoP validation. If intercepted, malicious actors can freely replay this token across any gateway endpoint without holding the original client private key.
```typescript
import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';

export function authenticateRequest(req: Request, res: Response, next: NextFunction) {
  const authHeader = req.headers.authorization;
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return res.status(401).json({ error: 'Missing bearer token' });
  }
  
  const token = authHeader.substring(7);
  try {
    // INSECURE: Bearer tokens are unbound and susceptible to token export/replay attacks
    const decoded = jwt.verify(token, process.env.JWT_PUBLIC_KEY!);
    req.user = decoded;
    next();
  } catch (err) {
    return res.status(401).json({ error: 'Invalid token' });
  }
}
```

#### Production Standard (Correct)
> **Standard**: Implements RFC 9449 end-to-end: asserts 'DPoP' scheme, validates token signature, enforces sender-constraint by calculating the JWK SHA-256 thumbprint against cnf.jkt, checks HTTP method/URL claims, and prevents proof replay using a distributed jti cache.
```typescript
import { Request, Response, NextFunction } from 'express';
import { createHash } from 'node:crypto';
import * as jose from 'jose';

interface DistributedNonceStore {
  consumeJti(jti: string, exp: number): Promise<boolean>;
}

declare const nonceStore: DistributedNonceStore;
declare const tokenVerifierJwks: jose.JWTVerifyGetKey;

export async function authenticateDPoPRequest(
  req: Request,
  res: Response,
  next: NextFunction
) {
  const authHeader = req.headers.authorization;
  const dpopHeader = req.headers.dpop as string | undefined;

  if (!authHeader?.startsWith('DPoP ') || !dpopHeader) {
    res.setHeader('WWW-Authenticate', 'DPoP error="invalid_token"');
    return res.status(401).json({ error: 'DPoP authentication token and proof header required' });
  }

  const rawAccessToken = authHeader.substring(6);

  try {
    // 1. Verify access token integrity and extract sender-constraint thumbprint
    const { payload: tokenPayload } = await jose.jwtVerify(rawAccessToken, tokenVerifierJwks);
    const expectedJkt = (tokenPayload.cnf as { jkt?: string })?.jkt;
    if (!expectedJkt) {
      return res.status(401).json({ error: 'Access token missing cnf.jkt binding' });
    }

    // 2. Decode DPoP proof header to obtain ephemeral client public JWK
    const unverifiedDPoP = jose.decodeProtectedHeader(dpopHeader);
    if (unverifiedDPoP.typ !== 'dpop+jwt' || !unverifiedDPoP.jwk) {
      return res.status(400).json({ error: 'Malformed DPoP header typ or missing embedded jwk' });
    }

    // 3. Verify public key thumbprint matches cnf.jkt in access token
    const computedThumbprint = await jose.calculateJwkThumbprint(unverifiedDPoP.jwk, 'sha256');
    if (computedThumbprint !== expectedJkt) {
      return res.status(401).json({ error: 'DPoP key thumbprint does not match token binding' });
    }

    // 4. Verify DPoP signature and bind to HTTP method/URI context
    const dpopKey = await jose.importJWK(unverifiedDPoP.jwk, unverifiedDPoP.alg);
    const reqUrl = `${req.protocol}://${req.get('host')}${req.path}`;
    
    const { payload: dpopPayload } = await jose.jwtVerify(dpopHeader, dpopKey, {
      typ: 'dpop+jwt',
      maxTokenAge: '60s',
    });

    if (dpopPayload.htm !== req.method || dpopPayload.htu !== reqUrl) {
      return res.status(401).json({ error: 'DPoP htm/htu mismatch with incoming request' });
    }

    // 5. Enforce single-use replay protection on the proof jti
    const jti = dpopPayload.jti;
    const iat = dpopPayload.iat || Math.floor(Date.now() / 1000);
    const isUnique = jti ? await nonceStore.consumeJti(jti, iat + 60) : false;
    if (!isUnique) {
      return res.status(401).json({ error: 'DPoP proof has already been used or missing jti' });
    }

    req.user = tokenPayload;
    next();
  } catch (err) {
    res.setHeader('WWW-Authenticate', 'DPoP error="invalid_dpop_proof"');
    return res.status(401).json({ error: 'DPoP cryptographic verification failed' });
  }
}
```

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 DPoP Ephemeral Asymmetric Key Binding Invariant

OAuth 2.1 DPoP Ephemeral Asymmetric Key Binding Invariant defines an industrial-grade behavioral standard for security engineering. Enforces RFC 9449 Demonstrating Proof-of-Possession (DPoP) across all client authentication flows and distributed API gateway verifiers. Requires access and refresh tokens to be cryptographically bound to ephemeral client-generated asymmetric key pairs via JWK thumbprints (cnf.jkt), eliminating token exfiltration and replay attacks across untrusted network perimeters. 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: Replay-Vulnerable Bearer Tokens and Unverified DPoP Proof Headers 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 DriftReplay-Vulnerable Bearer Tokens and Unverified DPoP Proof HeadersCritical
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-extractable asymmetric key pairs (ES256 / EdDSA) in memory or secure hardware enclave upon client initialization.

Engineers MUST ALWAYS generate ephemeral, non-extractable asymmetric key pairs (ES256 / EdDSA) in memory or secure hardware enclave upon client initialization.

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 keys to localStorage, unencrypted sessionStorage, or distributed caches where unauthorized scripts or processes could access them.

Engineers MUST NOT persist private keys to localStorage, unencrypted sessionStorage, or distributed caches where unauthorized scripts or processes could access them.

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

Services MUST validate the incoming 'DPoP' proof JWT by matching the 'htm' (HTTP method) and 'htu' (HTTP target URI excluding query/fragment) against the active request context.

Services MUST validate the incoming 'DPoP' proof JWT by matching the 'htm' (HTTP method) and 'htu' (HTTP target URI excluding query/fragment) against the active request context.

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

Distributed API Gateways MUST cryptographically verify that the SHA-256 thumbprint of the public key in the DPoP proof header matches the 'cnf.jkt' claim embedded within the sender-constrained access token.

Distributed API Gateways MUST cryptographically verify that the SHA-256 thumbprint of the public key in the DPoP proof header matches the 'cnf.jkt' claim embedded within the sender-constrained 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

Components NEVER accept Bearer tokens on protected endpoints configured for DPoP

Components NEVER accept Bearer tokens on protected endpoints configured for DPoP; mismatched token types MUST trigger a 401 Unauthorized with 'WWW-Authenticate: DPoP error="invalid_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.
6

Services MUST reject DPoP proof JWTs older than acceptable clock skew (recommended 60 seconds) and MUST enforce single-use replay protection using distributed cache checks on the proof 'jti'.

Services MUST reject DPoP proof JWTs older than acceptable clock skew (recommended 60 seconds) and MUST enforce single-use replay protection using distributed cache checks on the proof 'jti'.

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 DPoP Ephemeral Asymmetric Key Binding Invariant critical for AI coding assistants?

Enforces RFC 9449 Demonstrating Proof-of-Possession (DPoP) across all client authentication flows and distributed API gateway verifiers. Requires access and refresh tokens to be cryptographically bound to ephemeral client-generated asymmetric key pairs via JWK thumbprints (cnf.jkt), eliminating token exfiltration and replay attacks across untrusted network perimeters. 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 (Replay-Vulnerable Bearer Tokens and Unverified DPoP Proof Headers) 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