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

OAuth 2.1 RFC 9449 DPoP Sender-Constrained Nonce Rotation and Replay Prevention

Enforces RFC 9449 Demonstrating Proof-of-Possession (DPoP) bindings with dynamic server-issued nonce rotation and atomic jti replay caching across all mutating endpoints. Prevents bearer token exfiltration and distributed replay attacks by sender-constraining access tokens to client ephemeral asymmetric key pairs.

Prohibited Anti-Pattern: Accepting Unbound Bearer Tokens or DPoP Proofs Lacking Nonce Verification and Replay Validation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OAuth 2.1 RFC 9449 DPoP Sender-Constrained Nonce Rotation and Replay Prevention - Enforces RFC 9449 Demonstrating Proof-of-Possession (DPoP) bindings with dynamic server-issued nonce rotation and atomic jti replay caching across all mutating endpoints. Prevents bearer token exfiltration and distributed replay attacks by sender-constraining access tokens to client ephemeral asymmetric key pairs.
globs: src/auth/**/*.{ts,tsx}, src/middleware/**/*.{ts,tsx}, src/security/**/*.{ts,tsx}, src/api/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/oauth21-dpop-nonce-rotation-replay-guardrail"
---

# OAuth 2.1 RFC 9449 DPoP Sender-Constrained Nonce Rotation and Replay Prevention

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Accepting Unbound Bearer Tokens or DPoP Proofs Lacking Nonce Verification and Replay Validation

## System Constraints
You are a Principal Security Architect enforcing OAuth 2.1 and RFC 9449 standards. Reject all pull requests that allow unbound bearer tokens on state-changing endpoints, fail to rotate DPoP nonces, or omit distributed replay cache tracking for DPoP jti identifiers.

## Strict Guidelines
- Engineers MUST ALWAYS validate the DPoP proof's HTTP method (`htm`) and URI (`htu`) against the incoming HTTP request strictly normalized without query strings or fragments.
- Engineers MUST ALWAYS compute the SHA-256 thumbprint of the access token (`ath`) and verify its equality against the `ath` claim inside the DPoP proof JWT.
- Services MUST enforce server-provided nonce rotation via the `DPoP-Nonce` header; requests with missing or expired nonces MUST return HTTP 401 with `use_dpop_nonce` error code and a fresh nonce.
- Code MUST verify the cryptographic binding between the access token confirmation claim (`cnf.jkt`) and the SHA-256 JWK Thumbprint of the public key provided in the DPoP header.
- Components NEVER store or trust client-asserted asymmetric keys without verifying signature validity and asserting that the `typ` header equals `dpop+jwt`.
- Engineers MUST atomically register the DPoP `jti` in a distributed, memory-bounded store (e.g., Redis) with TTL matching the proof's validity window (maximum 120 seconds) to guarantee replay prevention.

## Bad vs Good Implementations
### DPoP Proof and Nonce Replay Verification Middleware

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Relies entirely on bearer tokens transmitted via Authorization header without sender-constraint. If leaked via logs, MITM, or compromised downstream microservices, the token can be replayed anywhere by any adversary without requiring client private key possession.
```typescript
import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';

// INSECURE: Accepts standard Bearer tokens without cryptographic binding
// Vulnerable to token theft, relay attacks, and token replay.
export async function verifyTokenMiddleware(req: Request, res: Response, next: NextFunction) {
  const authHeader = req.headers.authorization;
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return res.status(401).json({ error: 'unauthorized' });
  }

  const token = authHeader.split(' ')[1];
  try {
    const payload = jwt.verify(token, process.env.JWT_SECRET!);
    (req as any).user = payload;
    return next();
  } catch (err) {
    return res.status(401).json({ error: 'invalid_token' });
  }
}
```

#### Production Standard (Correct)
> **Standard**: Implements full RFC 9449 compliance: extracts ephemeral client public key from header, checks cryptographic signature, asserts exact URI/HTTP-method consistency, recalculates and checks the ath (access token hash), rotates server nonces on challenge, and uses an atomic cache primitive (NX) to prevent jti replay attacks.
```typescript
import { Request, Response, NextFunction } from 'express';
import { createHash } from 'node:crypto';
import * as jose from 'jose';
import { redisClient } from '../lib/redis';

interface ValidatedDPoPRequest extends Request {
  callerThumbprint?: string;
  tokenClaims?: jose.JWTPayload;
}

export async function dpopGuardrailMiddleware(
  req: ValidatedDPoPRequest,
  res: Response,
  next: NextFunction
): Promise<void> {
  const dpopProof = req.headers['dpop'] as string | undefined;
  const authHeader = req.headers.authorization;

  if (!dpopProof || !authHeader?.startsWith('DPoP ')) {
    res.set('WWW-Authenticate', 'DPoP error="invalid_token"');
    res.status(401).json({ error: 'dpop_required' });
    return;
  }

  const accessToken = authHeader.substring(5).trim();
  const expectedHtm = req.method.toUpperCase();
  const expectedHtu = `${req.protocol}://${req.get('host')}${req.baseUrl}${req.path}`;

  try {
    // 1. Verify DPoP Proof Header Structure and Asymmetric Signature
    const { payload: dpopPayload, protectedHeader } = await jose.jwtVerify(
      dpopProof,
      async (header) => {
        if (!header.jwk) throw new Error('Missing JWK in DPoP header');
        return jose.importJWK(header.jwk, header.alg);
      },
      { typ: 'dpop+jwt' }
    );

    // 2. Validate Nonce Rotation
    const activeNonce = await redisClient.get(`dpop_nonce:${req.ip}`);
    const incomingNonce = dpopPayload.nonce as string | undefined;
    if (!incomingNonce || incomingNonce !== activeNonce) {
      const newNonce = jose.base64url.encode(crypto.getRandomValues(new Uint8Array(32)));
      await redisClient.set(`dpop_nonce:${req.ip}`, newNonce, 'EX', 300);
      res.set('DPoP-Nonce', newNonce);
      res.set('WWW-Authenticate', 'DPoP error="use_dpop_nonce"');
      res.status(401).json({ error: 'use_dpop_nonce' });
      return;
    }

    // 3. Atomically Invalidate JTI to Prevent Replay
    const jti = dpopPayload.jti as string;
    const marked = await redisClient.set(`dpop_jti:${jti}`, '1', 'EX', 120, 'NX');
    if (!marked) {
      res.status(401).json({ error: 'dpop_jti_replayed' });
      return;
    }

    // 4. Validate htm, htu, and Access Token Hash (ath)
    const computedAth = jose.base64url.encode(
      createHash('sha256').update(accessToken).digest()
    );
    if (dpopPayload.htm !== expectedHtm || dpopPayload.htu !== expectedHtu || dpopPayload.ath !== computedAth) {
      res.status(401).json({ error: 'invalid_dpop_claims' });
      return;
    }

    // 5. Verify Access Token Confirmation (cnf.jkt) matches DPoP JWK Thumbprint
    const jwkThumbprint = await jose.calculateJwkThumbprint(protectedHeader.jwk!);
    const { payload: tokenPayload } = await jose.jwtVerify(accessToken, process.env.ACCESS_TOKEN_KEY!);
    const cnf = tokenPayload.cnf as { jkt: string } | undefined;

    if (!cnf || cnf.jkt !== jwkThumbprint) {
      res.status(401).json({ error: 'token_key_mismatch' });
      return;
    }

    req.callerThumbprint = jwkThumbprint;
    req.tokenClaims = tokenPayload;
    next();
  } catch (err) {
    res.status(401).json({ error: 'invalid_dpop_proof' });
  }
}
```

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 Nonce Rotation and Replay Prevention

OAuth 2.1 RFC 9449 DPoP Sender-Constrained Nonce Rotation and Replay Prevention defines an industrial-grade behavioral standard for security engineering. Enforces RFC 9449 Demonstrating Proof-of-Possession (DPoP) bindings with dynamic server-issued nonce rotation and atomic jti replay caching across all mutating endpoints. Prevents bearer token exfiltration and distributed replay attacks by sender-constraining access tokens to client ephemeral asymmetric key pairs. 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 DPoP Proofs Lacking Nonce Verification and Replay Validation 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 DPoP Proofs Lacking Nonce Verification and Replay ValidationCritical
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 validate the DPoP proof's HTTP method (`htm`) and URI (`htu`) against the incoming HTTP request strictly normalized without query strings or fragments.

Engineers MUST ALWAYS validate the DPoP proof's HTTP method (`htm`) and URI (`htu`) against the incoming HTTP request strictly normalized without query strings or fragments.

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 compute the SHA-256 thumbprint of the access token (`ath`) and verify its equality against the `ath` claim inside the DPoP proof JWT.

Engineers MUST ALWAYS compute the SHA-256 thumbprint of the access token (`ath`) and verify its equality against the `ath` claim inside the DPoP proof JWT.

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 enforce server-provided nonce rotation via the `DPoP-Nonce` header

Services MUST enforce server-provided nonce rotation via the `DPoP-Nonce` header; requests with missing or expired nonces MUST return HTTP 401 with `use_dpop_nonce` error code and a fresh nonce.

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

Code MUST verify the cryptographic binding between the access token confirmation claim (`cnf.jkt`) and the SHA-256 JWK Thumbprint of the public key provided in the DPoP header.

Code MUST verify the cryptographic binding between the access token confirmation claim (`cnf.jkt`) and the SHA-256 JWK Thumbprint of the public key provided in the DPoP 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.
5

Components NEVER store or trust client-asserted asymmetric keys without verifying signature validity and asserting that the `typ` header equals `dpop+jwt`.

Components NEVER store or trust client-asserted asymmetric keys without verifying signature validity and asserting that the `typ` header equals `dpop+jwt`.

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

Engineers MUST atomically register the DPoP `jti` in a distributed, memory-bounded store (e.g., Redis) with TTL matching the proof's validity window (maximum 120 seconds) to guarantee replay prevention.

Engineers MUST atomically register the DPoP `jti` in a distributed, memory-bounded store (e.g., Redis) with TTL matching the proof's validity window (maximum 120 seconds) to guarantee replay prevention.

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 Nonce Rotation and Replay Prevention critical for AI coding assistants?

Enforces RFC 9449 Demonstrating Proof-of-Possession (DPoP) bindings with dynamic server-issued nonce rotation and atomic jti replay caching across all mutating endpoints. Prevents bearer token exfiltration and distributed replay attacks by sender-constraining access tokens to client ephemeral asymmetric key pairs. 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 DPoP Proofs Lacking Nonce Verification and Replay Validation) 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