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

OAuth 2.1 RFC 9449 DPoP Token-Binding and Replay-Fencing Guardrail

Enforces asymmetric sender-constrained token binding and non-replayable proof validation per RFC 9449 (Demonstrating Proof-of-Possession). Mandates cryptographic validation of client ephemeral public keys, HTTP method/URI containment, access token hash (ath) binding, and distributed nonce/jti replay caching to eliminate bearer token exfiltration risks.

Prohibited Anti-Pattern: Accepting Unbound Bearer Tokens or Failing to Cryptographically Validate DPoP Proof Claims and Nonces

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OAuth 2.1 RFC 9449 DPoP Token-Binding and Replay-Fencing Guardrail - Enforces asymmetric sender-constrained token binding and non-replayable proof validation per RFC 9449 (Demonstrating Proof-of-Possession). Mandates cryptographic validation of client ephemeral public keys, HTTP method/URI containment, access token hash (ath) binding, and distributed nonce/jti replay caching to eliminate bearer token exfiltration risks.
globs: src/middleware/**/*.{ts,js}, src/auth/**/*.{ts,js}, src/security/**/*.{ts,js}, src/controllers/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/oauth-2-1-dpop-rfc-9449-token-binding-guardrail"
---

# OAuth 2.1 RFC 9449 DPoP Token-Binding and Replay-Fencing Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Accepting Unbound Bearer Tokens or Failing to Cryptographically Validate DPoP Proof Claims and Nonces

## System Constraints
You are a Principal Security Architect enforcing OAuth 2.1 RFC 9449 DPoP (Demonstrating Proof-of-Possession) token binding. Reject any implementation that treats tokens as bearer credentials without cryptographic proof of client key possession. Enforce asymmetric key algorithms, strict HTTP method and normalized URI matching, mandatory 'ath' thumbprint binding, single-use or time-bounded server nonces, and distributed JTI replay caching across all protected resource endpoints.

## Strict Guidelines
- Services MUST reject requests lacking a valid 'DPoP' header and require the Authorization header scheme to be 'DPoP' instead of 'Bearer'.
- Services MUST verify the DPoP proof JWT header contains typ: 'dpop+jwt' and an asymmetric algorithm (e.g., ES256, EdDSA, PS256); symmetric algorithms (HS256) and 'none' MUST be rejected.
- Services MUST verify the DPoP proof contains an embedded public key (jwk) without private key components, calculate its SHA-256 JWK thumbprint, and assert it equals the 'cnf.jkt' claim in the access token.
- Services MUST compute the SHA-256 base64url-encoded hash of the presented access token and assert exact match against the 'ath' claim in the DPoP proof.
- Services MUST validate that 'htm' matches the incoming HTTP request method and 'htu' matches the normalized canonical target URI (scheme, host, port, path, excluding query and fragment).
- Services MUST enforce server-managed nonces via the 'DPoP-Nonce' header; if missing, expired, or invalid, the service MUST reject with HTTP 401 and an updated 'DPoP-Nonce' header.
- Engineers MUST implement a distributed replay cache (e.g., Redis) to track DPoP 'jti' values within the allowed clock-skew window (maximum 60 seconds) to prevent replay attacks.
- Clients MUST generate ephemeral or secure-enclave hardware-backed asymmetric keys and sign each DPoP proof at request time, never reusing JTIs.

## Bad vs Good Implementations
### DPoP Proof and Token Binding Verification Middleware

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Accepts generic Bearer tokens without cryptographic proof of client key possession. Does not validate the DPoP header, allowing exfiltrated tokens to be used across different origins and clients without detection or replay fencing.
```typescript
import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';

// INSECURE: Standard Bearer verification vulnerable to token theft/replay
export async function authenticateToken(req: Request, res: Response, next: NextFunction) {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (!token) {
    return res.status(401).json({ error: 'Missing token' });
  }

  try {
    // Fails to bind sender identity; stolen bearer token can be freely replayed
    const payload = jwt.verify(token, process.env.JWT_PUBLIC_KEY!);
    req.user = payload;
    next();
  } catch (err) {
    return res.status(403).json({ error: 'Invalid token' });
  }
}
```

#### Production Standard (Correct)
> **Standard**: Implements RFC 9449 sender-constrained validation: enforces typ 'dpop+jwt', mandates asymmetric algorithms, verifies the embedded JWK thumbprint matches the token's 'cnf.jkt', calculates and verifies the 'ath' claim, enforces strict 'htm'/'htu' matching, and fends off replay attacks via Redis-backed JTI validation within a tight skew window.
```typescript
import { Request, Response, NextFunction } from 'express';
import { createHash } from 'node:crypto';
import * as jose from 'jose';
import { redisClient } from '../lib/redis';

const SKEW_SECONDS = 60;

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

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

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

  try {
    // 1. Decode unverified DPoP header to extract JWK
    const { header } = jose.decodeProtectedHeader(dpopHeader);
    if (header.typ !== 'dpop+jwt' || !header.jwk || header.alg?.startsWith('HS') || header.alg === 'none') {
      return res.status(400).json({ error: 'Invalid DPoP header or prohibited symmetric algorithm' });
    }

    const dpopPublicKey = await jose.importJWK(header.jwk, header.alg);

    // 2. Verify DPoP proof signature and claims
    const canonicalUrl = `${req.protocol}://${req.get('host')}${req.baseUrl}${req.path}`;
    const { payload: dpopPayload } = await jose.jwtVerify(dpopHeader, dpopPublicKey, {
      maxTokenAge: `${SKEW_SECONDS}s`,
      algorithms: ['ES256', 'PS256', 'EdDSA']
    });

    if (dpopPayload.htm !== req.method || dpopPayload.htu !== canonicalUrl) {
      return res.status(400).json({ error: 'DPoP htm/htu mismatch with canonical request target' });
    }

    // 3. Prevent replay attacks using distributed JTI cache
    const jtiKey = `dpop:jti:${dpopPayload.jti}`;
    const acquired = await redisClient.set(jtiKey, '1', { NX: true, EX: SKEW_SECONDS * 2 });
    if (!acquired) {
      return res.status(401).json({ error: 'DPoP proof jti already used' });
    }

    // 4. Validate Access Token and assert Sender-Constraint Binding (cnf.jkt)
    const expectedJkt = await jose.calculateJwkThumbprint(header.jwk, 'sha256');
    const { payload: tokenPayload } = await jose.jwtVerify(accessToken, jose.createRemoteJWKSet(new URL(process.env.JWKS_URI!)));

    const cnf = tokenPayload.cnf as { jkt?: string } | undefined;
    if (!cnf?.jkt || cnf.jkt !== expectedJkt) {
      return res.status(401).json({ error: 'Access token not bound to presented DPoP key' });
    }

    // 5. Assert Access Token Hash (ath) match
    const computedAth = createHash('sha256').update(accessToken).digest('base64url');
    if (dpopPayload.ath !== computedAth) {
      return res.status(400).json({ error: 'DPoP proof ath claim does not match access token' });
    }

    req.user = tokenPayload;
    next();
  } catch (err) {
    return res.status(401).setHeader('WWW-Authenticate', 'DPoP error="invalid_dpop_proof"').json({
      error: 'Cryptographic DPoP 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 RFC 9449 DPoP Token-Binding and Replay-Fencing Guardrail

OAuth 2.1 RFC 9449 DPoP Token-Binding and Replay-Fencing Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces asymmetric sender-constrained token binding and non-replayable proof validation per RFC 9449 (Demonstrating Proof-of-Possession). Mandates cryptographic validation of client ephemeral public keys, HTTP method/URI containment, access token hash (ath) binding, and distributed nonce/jti replay caching to eliminate bearer token exfiltration risks. 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: Accepting Unbound Bearer Tokens or Failing to Cryptographically Validate DPoP Proof Claims and Nonces 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 DriftAccepting Unbound Bearer Tokens or Failing to Cryptographically Validate DPoP Proof Claims and NoncesCritical
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

Services MUST reject requests lacking a valid 'DPoP' header and require the Authorization header scheme to be 'DPoP' instead of 'Bearer'.

Services MUST reject requests lacking a valid 'DPoP' header and require the Authorization header scheme to be 'DPoP' instead of 'Bearer'.

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

Services MUST verify the DPoP proof JWT header contains typ

Services MUST verify the DPoP proof JWT header contains typ: 'dpop+jwt' and an asymmetric algorithm (e.g., ES256, EdDSA, PS256); symmetric algorithms (HS256) and 'none' MUST be rejected.

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 verify the DPoP proof contains an embedded public key (jwk) without private key components, calculate its SHA-256 JWK thumbprint, and assert it equals the 'cnf.jkt' claim in the access token.

Services MUST verify the DPoP proof contains an embedded public key (jwk) without private key components, calculate its SHA-256 JWK thumbprint, and assert it equals the 'cnf.jkt' claim in 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

Services MUST compute the SHA-256 base64url-encoded hash of the presented access token and assert exact match against the 'ath' claim in the DPoP proof.

Services MUST compute the SHA-256 base64url-encoded hash of the presented access token and assert exact match against the 'ath' claim in the 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.
5

Services MUST validate that 'htm' matches the incoming HTTP request method and 'htu' matches the normalized canonical target URI (scheme, host, port, path, excluding query and fragment).

Services MUST validate that 'htm' matches the incoming HTTP request method and 'htu' matches the normalized canonical target URI (scheme, host, port, path, excluding query and fragment).

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 enforce server-managed nonces via the 'DPoP-Nonce' header

Services MUST enforce server-managed nonces via the 'DPoP-Nonce' header; if missing, expired, or invalid, the service MUST reject with HTTP 401 and an updated 'DPoP-Nonce' header.

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

Engineers MUST implement a distributed replay cache (e.g., Redis) to track DPoP 'jti' values within the allowed clock-skew window (maximum 60 seconds) to prevent replay attacks.

Engineers MUST implement a distributed replay cache (e.g., Redis) to track DPoP 'jti' values within the allowed clock-skew window (maximum 60 seconds) to prevent replay attacks.

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

Clients MUST generate ephemeral or secure-enclave hardware-backed asymmetric keys and sign each DPoP proof at request time, never reusing JTIs.

Clients MUST generate ephemeral or secure-enclave hardware-backed asymmetric keys and sign each DPoP proof at request time, never reusing JTIs.

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 Token-Binding and Replay-Fencing Guardrail critical for AI coding assistants?

Enforces asymmetric sender-constrained token binding and non-replayable proof validation per RFC 9449 (Demonstrating Proof-of-Possession). Mandates cryptographic validation of client ephemeral public keys, HTTP method/URI containment, access token hash (ath) binding, and distributed nonce/jti replay caching to eliminate bearer token exfiltration risks. 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 (Accepting Unbound Bearer Tokens or Failing to Cryptographically Validate DPoP Proof Claims and Nonces) 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