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

OAuth 2.1 RFC 9449 DPoP Proof and Nonce Replay Verification Invariant

Enforces RFC 9449 Demonstrating Proof-of-Possession (DPoP) at resource and authorization servers to prevent token theft and replay attacks. Mandates strict cryptographic verification of the ephemeral public key, HTTP method and URI bindings, access token hash (ath) validation, server-directed nonce rotation, and distributed jti replay prevention.

Prohibited Anti-Pattern: Bypassing DPoP proof signature validation, neglecting HTTP method/URI binding, omitting access token hash verification, or allowing jti replay.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OAuth 2.1 RFC 9449 DPoP Proof and Nonce Replay Verification Invariant - Enforces RFC 9449 Demonstrating Proof-of-Possession (DPoP) at resource and authorization servers to prevent token theft and replay attacks. Mandates strict cryptographic verification of the ephemeral public key, HTTP method and URI bindings, access token hash (ath) validation, server-directed nonce rotation, and distributed jti replay prevention.
globs: src/**/auth/**/*.{ts,tsx}, src/**/middleware/**/*.{ts,tsx}, src/**/security/**/*.{ts,tsx}, src/**/guards/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/oauth2-dpop-nonce-verification-standard"
---

# OAuth 2.1 RFC 9449 DPoP Proof and Nonce Replay Verification Invariant

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Bypassing DPoP proof signature validation, neglecting HTTP method/URI binding, omitting access token hash verification, or allowing jti replay.

## System Constraints
You are a Principal Security Architect enforcing OAuth 2.1 RFC 9449 (Demonstrating Proof-of-Possession). You must ensure all protected endpoints enforce cryptographic proof validation, ephemeral key verification, HTTP method and URI binding, SHA-256 access token hash (ath) validation, strict nonce lifetime enforcement, and atomic distributed jti replay protection.

## Strict Guidelines
- Services MUST verify that the DPoP proof header contains 'typ': 'dpop+jwt' and an asymmetric signature algorithm ('alg' MUST NOT be 'none' or symmetric 'HS*').
- Services MUST extract the public key directly from the JOSE header 'jwk' parameter and ensure it contains no private key components.
- Services MUST assert that the 'htm' claim strictly matches the uppercase HTTP request method and 'htu' matches the normalized target URI (scheme, authority, and path, excluding query and fragment).
- Resource servers MUST assert that the 'ath' claim in the DPoP proof matches the Base64URL-encoded SHA-256 hash of the presented access token.
- Services MUST enforce server-provided DPoP nonces ('nonce' claim) and reject missing or expired nonces with HTTP 401/400 and a 'use_dpop_nonce' error containing a fresh 'DPoP-Nonce' header.
- Services MUST track the 'jti' claim in a distributed cache (e.g., Redis) with an atomic SETNX/TTL operation matching the maximum proof lifetime window to prevent replay attacks.
- Engineers MUST NOT fall back to Bearer token semantics when a DPoP-bound token is supplied.

## Bad vs Good Implementations
### DPoP Proof Validation Middleware

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Decodes the DPoP proof without verifying its cryptographic signature against the embedded JWK, accepts arbitrary algorithms, fails to check that htm/htu match the request, ignores the access token hash (ath), does not validate server nonces, and lacks distributed replay prevention for the jti.
```typescript
import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';

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

  if (!dpopProof || !authHeader) {
    return res.status(401).json({ error: 'Missing credentials' });
  }

  // SECURITY FLAW: Unsafe decode without asymmetric verification against header JWK
  const decoded = jwt.decode(dpopProof) as any;
  
  // SECURITY FLAW: Missing 'htm', 'htu', 'ath' binding checks, and no jti replay cache
  if (decoded && decoded.jti) {
    return next();
  }
  return res.status(401).json({ error: 'Invalid DPoP proof' });
}
```

#### Production Standard (Correct)
> **Standard**: Complies strictly with RFC 9449: validates the 'dpop+jwt' header type and allowed asymmetric algorithms, verifies the cryptographic signature with the supplied JWK, enforces exact matches for HTTP method ('htm') and canonical URI ('htu'), validates the access token hash ('ath'), checks server nonces, and stores 'jti' in an atomic distributed replay cache.
```typescript
import { Request, Response, NextFunction } from 'express';
import crypto from 'node:crypto';
import * as jose from 'jose';

interface ReplayCache {
  setIfNotExists(jti: string, ttlSeconds: number): Promise<boolean>;
  isValidNonce(nonce: string): Promise<boolean>;
  generateNonce(): Promise<string>;
}

declare const replayCache: ReplayCache;
const ALLOWED_ALGS = ['ES256', 'ES384', 'ES512', 'EdDSA', 'PS256', 'PS384', 'PS512'];
const CLOCK_TOLERANCE_SECONDS = 60;

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

  if (typeof dpopHeader !== 'string' || typeof authHeader !== 'string') {
    return res.status(401).set('WWW-Authenticate', 'DPoP error="invalid_token"').json({ error: 'invalid_token' });
  }

  const [scheme, accessToken] = authHeader.split(' ');
  if (scheme !== 'DPoP' || !accessToken) {
    return res.status(401).json({ error: 'invalid_dpop_proof', message: 'Authorization scheme must be DPoP' });
  }

  try {
    // 1. Parse header without verification to extract JWK
    const header = jose.decodeProtectedHeader(dpopHeader);
    if (header.typ !== 'dpop+jwt' || !header.alg || !ALLOWED_ALGS.includes(header.alg) || !header.jwk) {
      return res.status(401).json({ error: 'invalid_dpop_proof', message: 'Invalid JOSE header parameters' });
    }

    // 2. Import public key and verify signature
    const publicKey = await jose.importJWK(header.jwk, header.alg);
    const { payload } = await jose.jwtVerify(dpopHeader, publicKey, {
      algorithms: ALLOWED_ALGS,
      clockTolerance: `${CLOCK_TOLERANCE_SECONDS}s`,
    });

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

    // 4. Validate Access Token Hash (ath)
    const expectedAth = crypto.createHash('sha256').update(accessToken).digest('base64url');
    if (payload.ath !== expectedAth) {
      return res.status(401).json({ error: 'invalid_dpop_proof', message: 'ath mismatch' });
    }

    // 5. Validate Server-Provided Nonce
    if (typeof payload.nonce !== 'string' || !(await replayCache.isValidNonce(payload.nonce))) {
      const freshNonce = await replayCache.generateNonce();
      return res.status(401)
        .set('DPoP-Nonce', freshNonce)
        .json({ error: 'use_dpop_nonce', message: 'Nonce is stale or missing' });
    }

    // 6. Enforce Distributed Replay Cache for JTI
    if (typeof payload.jti !== 'string') {
      return res.status(401).json({ error: 'invalid_dpop_proof', message: 'Missing jti' });
    }
    const isUnique = await replayCache.setIfNotExists(payload.jti, CLOCK_TOLERANCE_SECONDS * 2);
    if (!isUnique) {
      return res.status(401).json({ error: 'invalid_dpop_proof', message: 'DPoP proof replayed' });
    }

    next();
  } catch (err) {
    return res.status(401).json({ error: 'invalid_dpop_proof', message: (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: OAuth 2.1 RFC 9449 DPoP Proof and Nonce Replay Verification Invariant

OAuth 2.1 RFC 9449 DPoP Proof and Nonce Replay Verification Invariant defines an industrial-grade behavioral standard for security engineering. Enforces RFC 9449 Demonstrating Proof-of-Possession (DPoP) at resource and authorization servers to prevent token theft and replay attacks. Mandates strict cryptographic verification of the ephemeral public key, HTTP method and URI bindings, access token hash (ath) validation, server-directed nonce rotation, and distributed jti replay prevention. 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: Bypassing DPoP proof signature validation, neglecting HTTP method/URI binding, omitting access token hash verification, or allowing jti replay. 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 DriftBypassing DPoP proof signature validation, neglecting HTTP method/URI binding, omitting access token hash verification, or allowing jti replay.Critical
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 verify that the DPoP proof header contains 'typ'

Services MUST verify that the DPoP proof header contains 'typ': 'dpop+jwt' and an asymmetric signature algorithm ('alg' MUST NOT be 'none' or symmetric 'HS*').

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 extract the public key directly from the JOSE header 'jwk' parameter and ensure it contains no private key components.

Services MUST extract the public key directly from the JOSE header 'jwk' parameter and ensure it contains no private key components.

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 assert that the 'htm' claim strictly matches the uppercase HTTP request method and 'htu' matches the normalized target URI (scheme, authority, and path, excluding query and fragment).

Services MUST assert that the 'htm' claim strictly matches the uppercase HTTP request method and 'htu' matches the normalized target URI (scheme, authority, and 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.
4

Resource servers MUST assert that the 'ath' claim in the DPoP proof matches the Base64URL-encoded SHA-256 hash of the presented access token.

Resource servers MUST assert that the 'ath' claim in the DPoP proof matches the Base64URL-encoded SHA-256 hash of the presented 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 enforce server-provided DPoP nonces ('nonce' claim) and reject missing or expired nonces with HTTP 401/400 and a 'use_dpop_nonce' error containing a fresh 'DPoP-Nonce' header.

Services MUST enforce server-provided DPoP nonces ('nonce' claim) and reject missing or expired nonces with HTTP 401/400 and a 'use_dpop_nonce' error containing a fresh '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.
6

Services MUST track the 'jti' claim in a distributed cache (e.g., Redis) with an atomic SETNX/TTL operation matching the maximum proof lifetime window to prevent replay attacks.

Services MUST track the 'jti' claim in a distributed cache (e.g., Redis) with an atomic SETNX/TTL operation matching the maximum proof lifetime window 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.
7

Engineers MUST NOT fall back to Bearer token semantics when a DPoP-bound token is supplied.

Engineers MUST NOT fall back to Bearer token semantics when a DPoP-bound token is supplied.

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 Proof and Nonce Replay Verification Invariant critical for AI coding assistants?

Enforces RFC 9449 Demonstrating Proof-of-Possession (DPoP) at resource and authorization servers to prevent token theft and replay attacks. Mandates strict cryptographic verification of the ephemeral public key, HTTP method and URI bindings, access token hash (ath) validation, server-directed nonce rotation, and distributed jti replay prevention. 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 (Bypassing DPoP proof signature validation, neglecting HTTP method/URI binding, omitting access token hash verification, or allowing jti replay.) 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