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

OAuth 2.1 DPoP Token Binding and Server Nonce Rotation Invariant

Enforces strict RFC 9449 Demonstrating Proof-of-Possession (DPoP) binding across API gateways by requiring asymmetric client-key validation, SHA-256 access token hash verification (`ath`), and distributed single-use nonce rotation. Mitigates token exfiltration and replay attacks by rejecting standard Bearer authorizations on protected endpoints and invalidating stale or unbound DPoP proof headers.

Prohibited Anti-Pattern: Treating DPoP Proofs as Stateless Bearer Tokens Without Server Nonce Verification, Distributed Replay Detection, or Access Token Hash Binding

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OAuth 2.1 DPoP Token Binding and Server Nonce Rotation Invariant - Enforces strict RFC 9449 Demonstrating Proof-of-Possession (DPoP) binding across API gateways by requiring asymmetric client-key validation, SHA-256 access token hash verification (`ath`), and distributed single-use nonce rotation. Mitigates token exfiltration and replay attacks by rejecting standard Bearer authorizations on protected endpoints and invalidating stale or unbound DPoP proof headers.
globs: src/auth/**/*.{ts,tsx,js}, src/middleware/**/*.{ts,tsx,js}, src/gateway/**/*.{ts,tsx,js}, src/controllers/**/*.{ts,tsx,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/oauth-dpop-nonce-rotation-binding"
---

# OAuth 2.1 DPoP Token Binding and Server Nonce Rotation Invariant

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Treating DPoP Proofs as Stateless Bearer Tokens Without Server Nonce Verification, Distributed Replay Detection, or Access Token Hash Binding

## System Constraints
You are a Principal Security Architect enforcing OAuth 2.1 (RFC 9449) DPoP invariants. You must mandate strict cryptographic proof verification, access token hash (ath) checking, public key thumbprint binding (cnf.jkt), and distributed server-nonce rotation. Reject any implementation that accepts unbound bearer tokens on DPoP-required routes or relies on ephemeral in-memory nonce caches.

## Strict Guidelines
- Engineers MUST ALWAYS verify that the incoming Authorization scheme is 'DPoP' and reject 'Bearer' schemes on DPoP-enforced endpoints.
- Engineers MUST ALWAYS validate the DPoP proof header contains typ 'dpop+jwt' and an embedded ephemeral or bound public JWK.
- Services MUST compute the SHA-256 base64url thumbprint (RFC 7638) of the DPoP proof's public key and assert exact equality with the 'cnf.jkt' claim inside the access token.
- Services MUST verify the 'ath' (Access Token Hash) claim within the DPoP proof payload against the base64url SHA-256 digest of the raw incoming access token string.
- Services MUST validate the 'htm' (HTTP method) and 'htu' (HTTP target URI excluding query and fragment) claims against the current HTTP request.
- Services MUST validate server-issued DPoP nonces using a distributed replay store (e.g., Redis atomic consumption) and return HTTP 401 with a fresh 'DPoP-Nonce' header when nonces are stale, missing, or previously consumed.
- Components NEVER store or check DPoP 'jti' identifiers in local node process memory; all replay checks MUST execute atomically against a distributed store with an explicit TTL.

## Bad vs Good Implementations
### DPoP Verification and Nonce Rotation Guardrail

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Accepts generic Bearer headers, fails to verify the DPoP proof signature and typ header, completely ignores the 'ath' claim binding the proof to the access token, skips server nonce validation, and uses a process-local Set for JTI replay detection that fails across multi-node distributed API gateways.
```typescript
import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';

// ANTI-PATTERN: Fails RFC 9449 compliance.
// 1. Accepts Bearer tokens fallback.
// 2. Ignores 'ath' (Access Token Hash) binding.
// 3. Omits distributed server nonce verification.
// 4. In-memory replay set leaks memory and fails across multiple instances.
const seenJtis = new Set<string>();

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

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

  const token = authHeader.replace(/^Bearer /i, '').replace(/^DPoP /i, '');
  const proofPayload = jwt.decode(dpopHeader) as any;

  if (seenJtis.has(proofPayload.jti)) {
    return res.status(401).json({ error: 'Replay detected' });
  }
  seenJtis.add(proofPayload.jti);

  req.user = jwt.decode(token);
  return next();
}
```

#### Production Standard (Correct)
> **Standard**: Implements full RFC 9449 compliance: validates typ 'dpop+jwt', verifies the embedded public key matches the access token's 'cnf.jkt' thumbprint, validates 'ath', 'htm', and 'htu', and performs atomic distributed nonce rotation and JTI anti-replay caching in Redis.
```typescript
import { Request, Response, NextFunction } from 'express';
import { createHash } from 'node:crypto';
import { calculateJwkThumbprint, jwtVerify, importJWK } from 'jose';
import { Redis } from 'ioredis';

interface DPoPClaims {
  jti: string;
  htm: string;
  htu: string;
  iat: number;
  ath: string;
  nonce: string;
}

const redis = new Redis(process.env.REDIS_URL!);
const MAX_PROOF_AGE_SEC = 60;

function base64UrlSha256(input: string): string {
  return createHash('sha256').update(input, 'utf8').digest('base64url');
}

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

    if (!authHeader?.startsWith('DPoP ') || !dpopHeader) {
      const freshNonce = await generateAndStoreNonce();
      res.setHeader('DPoP-Nonce', freshNonce);
      return res.status(401).json({ error: 'invalid_dpop_proof', error_description: 'DPoP header required with DPoP scheme' });
    }

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

    try {
      // 1. Verify access token signature and extract cnf.jkt
      const { payload: atPayload } = await jwtVerify(rawAccessToken, getAccessTokenKey);
      const cnfJkt = (atPayload.cnf as { jkt?: string })?.jkt;
      if (!cnfJkt) {
        return res.status(403).json({ error: 'unbound_access_token', error_description: 'Access token lacks cnf.jkt binding' });
      }

      // 2. Decode and verify DPoP proof JWT
      const { payload: proof, protectedHeader } = await jwtVerify<DPoPClaims>(dpopHeader, async (header) => {
        if (header.typ !== 'dpop+jwt' || !header.jwk) {
          throw new Error('Invalid DPoP header typography or missing JWK');
        }
        return importJWK(header.jwk, header.alg);
      });

      // 3. Verify JWK thumbprint matches cnf.jkt
      const clientJwkThumbprint = await calculateJwkThumbprint(protectedHeader.jwk!);
      if (clientJwkThumbprint !== cnfJkt) {
        return res.status(401).json({ error: 'invalid_token_binding', error_description: 'JWK does not match cnf.jkt thumbprint' });
      }

      // 4. Verify HTTP Method, Target URI, and Access Token Hash (ath)
      const targetUri = `${expectedHtuBase}${req.baseUrl}${req.path}`;
      if (proof.htm !== req.method || proof.htu !== targetUri) {
        return res.status(401).json({ error: 'invalid_dpop_proof', error_description: 'htm/htu mismatch' });
      }
      if (proof.ath !== base64UrlSha256(rawAccessToken)) {
        return res.status(401).json({ error: 'invalid_dpop_proof', error_description: 'ath mismatch' });
      }

      // 5. Distributed atomic Nonce consumption and JTI replay check
      const isNonceValid = await redis.del(`dpop:nonce:${proof.nonce}`);
      if (!isNonceValid) {
        const freshNonce = await generateAndStoreNonce();
        res.setHeader('DPoP-Nonce', freshNonce);
        return res.status(401).json({ error: 'use_dpop_nonce', error_description: 'Invalid or expired DPoP nonce' });
      }

      const jtiRegistered = await redis.set(`dpop:jti:${proof.jti}`, '1', 'EX', MAX_PROOF_AGE_SEC, 'NX');
      if (!jtiRegistered) {
        return res.status(401).json({ error: 'invalid_dpop_proof', error_description: 'JTI replay detected' });
      }

      // Supply fresh nonce for next request in mutual rotation
      res.setHeader('DPoP-Nonce', await generateAndStoreNonce());
      req.user = atPayload;
      return next();
    } catch (err) {
      return res.status(401).json({ error: 'invalid_dpop_proof', error_description: (err as Error).message });
    }
  };
}

async function generateAndStoreNonce(): Promise<string> {
  const nonce = createHash('sha256').update(crypto.randomUUID()).digest('base64url');
  await redis.set(`dpop:nonce:${nonce}`, '1', 'EX', 300); // 5 min nonce validity
  return nonce;
}

async function getAccessTokenKey() {
  // Access token public verification key retrieval implementation
  return Buffer.from(process.env.AT_PUBLIC_KEY!, 'base64');
}
```

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 Token Binding and Server Nonce Rotation Invariant

OAuth 2.1 DPoP Token Binding and Server Nonce Rotation Invariant defines an industrial-grade behavioral standard for security engineering. Enforces strict RFC 9449 Demonstrating Proof-of-Possession (DPoP) binding across API gateways by requiring asymmetric client-key validation, SHA-256 access token hash verification (`ath`), and distributed single-use nonce rotation. Mitigates token exfiltration and replay attacks by rejecting standard Bearer authorizations on protected endpoints and invalidating stale or unbound DPoP proof headers. 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: Treating DPoP Proofs as Stateless Bearer Tokens Without Server Nonce Verification, Distributed Replay Detection, or Access Token Hash Binding 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 DriftTreating DPoP Proofs as Stateless Bearer Tokens Without Server Nonce Verification, Distributed Replay Detection, or Access Token Hash BindingCritical
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 verify that the incoming Authorization scheme is 'DPoP' and reject 'Bearer' schemes on DPoP-enforced endpoints.

Engineers MUST ALWAYS verify that the incoming Authorization scheme is 'DPoP' and reject 'Bearer' schemes on DPoP-enforced endpoints.

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 ALWAYS validate the DPoP proof header contains typ 'dpop+jwt' and an embedded ephemeral or bound public JWK.

Engineers MUST ALWAYS validate the DPoP proof header contains typ 'dpop+jwt' and an embedded ephemeral or bound public JWK.

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 compute the SHA-256 base64url thumbprint (RFC 7638) of the DPoP proof's public key and assert exact equality with the 'cnf.jkt' claim inside the access token.

Services MUST compute the SHA-256 base64url thumbprint (RFC 7638) of the DPoP proof's public key and assert exact equality with the 'cnf.jkt' claim inside 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 verify the 'ath' (Access Token Hash) claim within the DPoP proof payload against the base64url SHA-256 digest of the raw incoming access token string.

Services MUST verify the 'ath' (Access Token Hash) claim within the DPoP proof payload against the base64url SHA-256 digest of the raw incoming access token string.

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 the 'htm' (HTTP method) and 'htu' (HTTP target URI excluding query and fragment) claims against the current HTTP request.

Services MUST validate the 'htm' (HTTP method) and 'htu' (HTTP target URI excluding query and fragment) claims against the current HTTP request.

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 validate server-issued DPoP nonces using a distributed replay store (e.g., Redis atomic consumption) and return HTTP 401 with a fresh 'DPoP-Nonce' header when nonces are stale, missing, or previously consumed.

Services MUST validate server-issued DPoP nonces using a distributed replay store (e.g., Redis atomic consumption) and return HTTP 401 with a fresh 'DPoP-Nonce' header when nonces are stale, missing, or previously consumed.

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

Components NEVER store or check DPoP 'jti' identifiers in local node process memory

Components NEVER store or check DPoP 'jti' identifiers in local node process memory; all replay checks MUST execute atomically against a distributed store with an explicit TTL.

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 Token Binding and Server Nonce Rotation Invariant critical for AI coding assistants?

Enforces strict RFC 9449 Demonstrating Proof-of-Possession (DPoP) binding across API gateways by requiring asymmetric client-key validation, SHA-256 access token hash verification (`ath`), and distributed single-use nonce rotation. Mitigates token exfiltration and replay attacks by rejecting standard Bearer authorizations on protected endpoints and invalidating stale or unbound DPoP proof headers. 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 (Treating DPoP Proofs as Stateless Bearer Tokens Without Server Nonce Verification, Distributed Replay Detection, or Access Token Hash Binding) 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