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

OAuth 2.1 DPoP Sender-Constrained Nonce Rotation and Distributed Replay Guardrail

Enforces sender-constrained token access via RFC 9449 Demonstrating Proof-of-Possession (DPoP) across distributed edge gateways. Mandates asymmetric key proof validation, strict HTTP method and URI binding, SHA-256 access token thumbprint validation (ath), and distributed atomic nonce rotation to neutralize access-token exfiltration and replay attacks.

Prohibited Anti-Pattern: Accepting Bearer Tokens or Unchecked DPoP Proofs with Stale Nonces and Missing ATH Bindings

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OAuth 2.1 DPoP Sender-Constrained Nonce Rotation and Distributed Replay Guardrail - Enforces sender-constrained token access via RFC 9449 Demonstrating Proof-of-Possession (DPoP) across distributed edge gateways. Mandates asymmetric key proof validation, strict HTTP method and URI binding, SHA-256 access token thumbprint validation (ath), and distributed atomic nonce rotation to neutralize access-token exfiltration and replay attacks.
globs: src/auth/**/*.{ts,js}, src/middleware/**/*.{ts,js}, src/gateway/**/*.{ts,js}, src/security/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/oauth-21-dpop-nonce-rotation-replay-guardrail"
---

# OAuth 2.1 DPoP Sender-Constrained Nonce Rotation and Distributed Replay Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Accepting Bearer Tokens or Unchecked DPoP Proofs with Stale Nonces and Missing ATH Bindings

## System Constraints
You are a Principal Security Architect enforcing OAuth 2.1 Demonstrating Proof-of-Possession (DPoP, RFC 9449) across edge gateways and resource servers. You must prohibit conventional Bearer token validation on sensitive endpoints and enforce sender-constrained asymmetric cryptographic proof checks. Reject any implementation that permits missing 'ath' (access token hash) claims, missing or unchecked 'jti' nonces, unvalidated HTTP URI/method match, or unrotated server-side nonces.

## Strict Guidelines
- Edge gateways and resource servers MUST require the 'DPoP' proof header alongside the 'DPoP <access_token>' Authorization header for all protected endpoints.
- Validators MUST extract the public key directly from the DPoP proof's JOSE Header ('jwk') and reject symmetric algorithms (e.g., 'HS256') or missing 'jwk' declarations.
- Validators MUST compute the SHA-256 thumbprint (jkt) of the presented public JWK and assert identity against the 'jkt' confirmation claim ('cnf.jkt') bound inside the access token JWT.
- Validators MUST compute the base64url-encoded SHA-256 digest of the raw incoming access token string and verify an exact match against the 'ath' claim in the DPoP proof payload.
- Edge proxies MUST validate that 'htm' (HTTP method) and 'htu' (HTTP URI normalized without query/fragment) in the DPoP proof payload strictly match the incoming HTTP request context.
- Validators MUST reject DPoP proofs whose 'iat' timestamp exceeds a clock skew limit (maximum 60 seconds) or is in the future.
- Distributed resource gateways MUST record and verify the DPoP 'jti' identifier against a shared low-latency distributed store (e.g., Redis or DynamoDB with TTL) using an atomic test-and-set operation to prevent proof replay within the validity window.
- When a client presents an expired, missing, or rotated server-generated nonce, servers MUST immediately reject the request with HTTP 401, error code 'use_dpop_nonce', and issue a fresh cryptographically signed nonce via the 'DPoP-Nonce' HTTP response header.

## Bad vs Good Implementations
### RFC 9449 DPoP Edge Validation with ATH, JKT, and Distributed Nonce Enforcement

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Accepts standard unconstrained Bearer tokens without DPoP proof verification. If the access token is exfiltrated from client storage or intercepted in transit, an attacker can replay it freely against any resource server.
```typescript
import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';

export async function badAuthMiddleware(req: Request, res: Response, next: NextFunction) {
  const authHeader = req.headers.authorization;
  // Flaw 1: Accepts standard Bearer tokens without sender-constraining
  if (!authHeader?.startsWith('Bearer ')) {
    return res.status(401).json({ error: 'unauthorized' });
  }

  const token = authHeader.substring(7);
  try {
    // Flaw 2: Only verifies token signature, vulnerable to exfiltration/replay
    const decoded = jwt.verify(token, process.env.JWT_PUBLIC_KEY!);
    req.user = decoded;
    return next();
  } catch (err) {
    return res.status(401).json({ error: 'invalid_token' });
  }
}
```

#### Production Standard (Correct)
> **Standard**: Implements full RFC 9449 compliance: extracts and verifies client public JWK, asserts sender-constraining via token 'cnf.jkt' and 'ath' matching, validates HTM/HTU bindings, rotates nonces with standard error codes, and enforces distributed atomic replay protection via Redis.
```typescript
import { Request, Response, NextFunction } from 'express';
import { createHash } from 'node:crypto';
import * as jose from 'jose';
import type { Redis } from 'ioredis';

interface SecureRequest extends Request {
  user?: jose.JWTPayload;
}

export function createDPoPValidator(redis: Redis, gatewayUrl: string, expectedAudience: string) {
  return async function dpopAuthMiddleware(req: SecureRequest, res: Response, next: NextFunction) {
    const authHeader = req.headers.authorization;
    const dpopHeader = req.headers['dpop'];

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

    const rawAccessToken = authHeader.substring(6).trim();

    try {
      // 1. Verify DPoP Proof Structure & Signature using embedded JWK
      const { payload: dpopPayload, protectedHeader } = await jose.jwtVerify(dpopHeader, async (header) => {
        if (!header.jwk || header.typ !== 'dpop+jwt' || header.alg.startsWith('HS')) {
          throw new Error('Invalid DPoP header parameters');
        }
        return jose.importJWK(header.jwk, header.alg);
      });

      // 2. HTTP Method and Normalised URI Binding
      const expectedUri = `${gatewayUrl}${req.baseUrl}${req.path}`;
      if (dpopPayload.htm !== req.method || dpopPayload.htu !== expectedUri) {
        return res.status(401).json({ error: 'invalid_dpop_proof', description: 'HTTP binding mismatch' });
      }

      // 3. Validate Server Nonce (atomic rotation / check)
      const expectedNonce = await redis.get(`dpop:nonce:${dpopPayload.jti}`);
      if (dpopPayload.nonce !== req.headers['x-expected-dpop-nonce']) {
        const freshNonce = jose.base64url.encode(crypto.getRandomValues(new Uint8Array(32)));
        res.setHeader('DPoP-Nonce', freshNonce);
        res.setHeader('WWW-Authenticate', 'DPoP error="use_dpop_nonce"');
        return res.status(401).json({ error: 'use_dpop_nonce' });
      }

      // 4. Anti-Replay: Atomic SETNX on jti within validity window (60s)
      const replayGuardKey = `dpop:replay:${dpopPayload.jti}`;
      const isNew = await redis.set(replayGuardKey, '1', 'EX', 60, 'NX');
      if (!isNew) {
        return res.status(401).json({ error: 'invalid_dpop_proof', description: 'Replay detected' });
      }

      // 5. Verify Access Token and assert Sender-Constraining (cnf.jkt and ath)
      const { payload: tokenPayload } = await jose.jwtVerify(rawAccessToken, jose.createRemoteJWKSet(new URL(`${gatewayUrl}/.well-known/jwks.json`)), {
        audience: expectedAudience
      });

      const clientJwk = protectedHeader.jwk!;
      const calculatedJkt = await jose.calculateJwkThumbprint(clientJwk, 'sha256');
      const cnf = tokenPayload.cnf as { jkt?: string } | undefined;

      if (!cnf?.jkt || cnf.jkt !== calculatedJkt) {
        return res.status(401).json({ error: 'invalid_token', description: 'DPoP key does not match token thumbprint' });
      }

      // 6. Access Token Hash (ath) validation
      const calculatedAth = jose.base64url.encode(createHash('sha256').update(rawAccessToken).digest());
      if (dpopPayload.ath !== calculatedAth) {
        return res.status(401).json({ error: 'invalid_dpop_proof', description: 'Access token hash mismatch' });
      }

      req.user = tokenPayload;
      return next();
    } catch (err) {
      return res.status(401).json({ error: 'invalid_dpop_proof', description: (err as Error).message });
    }
  };
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OAuth 2.1 DPoP Sender-Constrained Nonce Rotation and Distributed Replay Guardrail

OAuth 2.1 DPoP Sender-Constrained Nonce Rotation and Distributed Replay Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces sender-constrained token access via RFC 9449 Demonstrating Proof-of-Possession (DPoP) across distributed edge gateways. Mandates asymmetric key proof validation, strict HTTP method and URI binding, SHA-256 access token thumbprint validation (ath), and distributed atomic nonce rotation to neutralize access-token exfiltration and replay attacks. 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 Bearer Tokens or Unchecked DPoP Proofs with Stale Nonces and Missing ATH Bindings 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 Bearer Tokens or Unchecked DPoP Proofs with Stale Nonces and Missing ATH BindingsCritical
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

Edge gateways and resource servers MUST require the 'DPoP' proof header alongside the 'DPoP <access_token>' Authorization header for all protected endpoints.

Edge gateways and resource servers MUST require the 'DPoP' proof header alongside the 'DPoP <access_token>' Authorization header for all protected 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

Validators MUST extract the public key directly from the DPoP proof's JOSE Header ('jwk') and reject symmetric algorithms (e.g., 'HS256') or missing 'jwk' declarations.

Validators MUST extract the public key directly from the DPoP proof's JOSE Header ('jwk') and reject symmetric algorithms (e.g., 'HS256') or missing 'jwk' declarations.

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

Validators MUST compute the SHA-256 thumbprint (jkt) of the presented public JWK and assert identity against the 'jkt' confirmation claim ('cnf.jkt') bound inside the access token JWT.

Validators MUST compute the SHA-256 thumbprint (jkt) of the presented public JWK and assert identity against the 'jkt' confirmation claim ('cnf.jkt') bound inside the access token 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.
4

Validators MUST compute the base64url-encoded SHA-256 digest of the raw incoming access token string and verify an exact match against the 'ath' claim in the DPoP proof payload.

Validators MUST compute the base64url-encoded SHA-256 digest of the raw incoming access token string and verify an exact match against the 'ath' claim in the DPoP proof payload.

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

Edge proxies MUST validate that 'htm' (HTTP method) and 'htu' (HTTP URI normalized without query/fragment) in the DPoP proof payload strictly match the incoming HTTP request context.

Edge proxies MUST validate that 'htm' (HTTP method) and 'htu' (HTTP URI normalized without query/fragment) in the DPoP proof payload strictly match the incoming HTTP 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.
6

Validators MUST reject DPoP proofs whose 'iat' timestamp exceeds a clock skew limit (maximum 60 seconds) or is in the future.

Validators MUST reject DPoP proofs whose 'iat' timestamp exceeds a clock skew limit (maximum 60 seconds) or is in the future.

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

Distributed resource gateways MUST record and verify the DPoP 'jti' identifier against a shared low-latency distributed store (e.g., Redis or DynamoDB with TTL) using an atomic test-and-set operation to prevent proof replay within the validity window.

Distributed resource gateways MUST record and verify the DPoP 'jti' identifier against a shared low-latency distributed store (e.g., Redis or DynamoDB with TTL) using an atomic test-and-set operation to prevent proof replay within the validity window.

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

When a client presents an expired, missing, or rotated server-generated nonce, servers MUST immediately reject the request with HTTP 401, error code 'use_dpop_nonce', and issue a fresh cryptographically signed nonce via the 'DPoP-Nonce' HTTP response header.

When a client presents an expired, missing, or rotated server-generated nonce, servers MUST immediately reject the request with HTTP 401, error code 'use_dpop_nonce', and issue a fresh cryptographically signed nonce via the 'DPoP-Nonce' HTTP response 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.
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 Sender-Constrained Nonce Rotation and Distributed Replay Guardrail critical for AI coding assistants?

Enforces sender-constrained token access via RFC 9449 Demonstrating Proof-of-Possession (DPoP) across distributed edge gateways. Mandates asymmetric key proof validation, strict HTTP method and URI binding, SHA-256 access token thumbprint validation (ath), and distributed atomic nonce rotation to neutralize access-token exfiltration and replay attacks. 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 Bearer Tokens or Unchecked DPoP Proofs with Stale Nonces and Missing ATH Bindings) 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