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

FAPI 2.0 DPoP Nonce Replay Prevention and Asymmetric Token Binding

Enforces RFC 9449 Demonstrating Proof-of-Possession (DPoP) and FAPI 2.0 security profile invariants across OAuth 2.0 token issuance and resource access. Prevents token replay, credential theft, and man-in-the-middle attacks by mandating cryptographic key-binding of access tokens via the 'cnf.jkt' thumbprint claim and strictly validating server-supplied single-use nonces with jitter-bounded clock drift.

Prohibited Anti-Pattern: Accepting Unbound Bearer Tokens or Permitting Unvalidated, Cached, or Replayed DPoP Proofs

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: FAPI 2.0 DPoP Nonce Replay Prevention and Asymmetric Token Binding - Enforces RFC 9449 Demonstrating Proof-of-Possession (DPoP) and FAPI 2.0 security profile invariants across OAuth 2.0 token issuance and resource access. Prevents token replay, credential theft, and man-in-the-middle attacks by mandating cryptographic key-binding of access tokens via the 'cnf.jkt' thumbprint claim and strictly validating server-supplied single-use nonces with jitter-bounded clock drift.
globs: src/auth/**/*.ts, src/middleware/**/*.ts, src/security/**/*.ts, src/gateway/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/fapi2-dpop-nonce-replay-token-binding"
---

# FAPI 2.0 DPoP Nonce Replay Prevention and Asymmetric Token Binding

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Accepting Unbound Bearer Tokens or Permitting Unvalidated, Cached, or Replayed DPoP Proofs

## System Constraints
You are a Principal Security Architect enforcing FAPI 2.0 and RFC 9449 DPoP (Demonstrating Proof-of-Possession) security invariants. Never permit fallback to bearer tokens when DPoP is configured. Always mandate cryptographic verification of ephemeral proof JWTs: enforce 'typ' header as 'dpop+jwt', validate client public key thumbprint match ('jkt') against access token 'cnf.jkt', verify 'htm' and 'htu' (canonical method and URI without query/fragment), and validate server nonces against an atomic, single-use distributed store with strict TTL to eliminate replay attacks.

## Strict Guidelines
- Engineers MUST ALWAYS verify that the DPoP proof JWT header contains 'typ': 'dpop+jwt' and an asymmetric JWK in the 'jwk' header parameter without a private key component.
- Engineers MUST ALWAYS calculate the SHA-256 JWK thumbprint ('jkt') of the public key in the DPoP proof and match it against the 'cnf.jkt' claim embedded in the sender-constrained access token.
- Engineers MUST ALWAYS validate the 'htm' (HTTP method) and 'htu' (HTTP URI without query or fragment parameters) claims against the incoming HTTP request context.
- Services MUST enforce server-provided 'nonce' claims in DPoP proofs, validating them against an atomic, single-use cache (e.g., Redis GETDEL) with strict TTL (<= 300 seconds) to prevent replay.
- Services MUST reject DPoP proof timestamps ('iat') that drift beyond a 60-second window relative to server time.
- Components NEVER fall back to standard Bearer token authorization headers when a route or client is configured for FAPI 2.0 DPoP.
- Code SHOULD verify the 'ath' (access token hash) claim in resource access DPoP proofs by computing base64url(sha256(raw_access_token)).

## Bad vs Good Implementations
### DPoP Proof Validation and Access Token Cryptographic Binding Middleware

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Accepts unconstrained bearer tokens, decodes the DPoP proof without verifying the cryptographic signature against the declared ephemeral public key, fails to validate the 'htm' and 'htu' claims, ignores access token hash ('ath') binding, and does not check or revoke single-use nonces, permitting replay and token theft.
```typescript
import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';

export async function badDpopMiddleware(req: Request, res: Response, next: NextFunction) {
  const token = req.headers.authorization?.replace(/^Bearer /i, '');
  const dpopHeader = req.headers['dpop'] as string;

  // VULNERABLE: Allows bearer tokens, does not bind key thumbprint,
  // ignores nonce replay, does not validate htm/htu canonicalization
  if (!token) {
    return res.status(401).json({ error: 'Missing token' });
  }

  try {
    const payload = jwt.verify(token, process.env.JWT_SECRET!) as jwt.JwtPayload;
    if (dpopHeader) {
      // Insecure: Decode without verifying signature against embedded JWK
      const dpopProof = jwt.decode(dpopHeader) as jwt.JwtPayload;
      if (!dpopProof) {
        return res.status(400).json({ error: 'Malformed DPoP' });
      }
    }
    req.user = payload;
    next();
  } catch (err) {
    return res.status(401).json({ error: 'Invalid token' });
  }
}
```

#### Production Standard (Correct)
> **Standard**: Implements full RFC 9449 and FAPI 2.0 invariants: rejects non-DPoP schemes, enforces 'typ: dpop+jwt', verifies the asymmetric signature using the embedded JWK, computes the 'jkt' thumbprint and matches it to 'cnf.jkt' in the access token, validates 'ath', checks canonical 'htm' and 'htu', and performs atomic single-use nonce consumption via Redis GETDEL to defeat replay attacks.
```typescript
import { Request, Response, NextFunction } from 'express';
import { createHash } from 'node:crypto';
import * as jose from 'jose';
import { Redis } from 'ioredis';

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

export function createDPoPVerifier(redis: Redis, resourceServerBaseUrl: string) {
  return async function dpopGuard(req: SecureRequest, res: Response, next: NextFunction): Promise<void> {
    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 scheme required"');
      res.status(401).json({ error: 'invalid_dpop' });
      return;
    }

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

    try {
      // 1. Verify DPoP Proof Header and Cryptographic Signature
      const { payload: proof, protectedHeader } = await jose.jwtVerify(dpopHeader, async (header) => {
        if (header.typ !== 'dpop+jwt' || !header.jwk) {
          throw new Error('Invalid DPoP header typography or missing embedded JWK');
        }
        return jose.importJWK(header.jwk, header.alg);
      });

      if (!protectedHeader.jwk) throw new Error('Missing JWK');
      const calculatedJkt = await jose.calculateJwkThumbprint(protectedHeader.jwk, 'sha256');

      // 2. Validate HTM and HTU (Normalized)
      const expectedUri = `${resourceServerBaseUrl}${req.baseUrl}${req.path}`;
      if (proof.htm !== req.method.toUpperCase() || proof.htu !== expectedUri) {
        res.status(400).json({ error: 'invalid_dpop_proof', error_description: 'htm/htu mismatch' });
        return;
      }

      // 3. Prevent Replay: Validate and Invalidate Server Nonce Atomically
      const nonce = proof.nonce;
      if (typeof nonce !== 'string') {
        const newNonce = crypto.randomUUID();
        await redis.set(`dpop:nonce:${newNonce}`, '1', 'EX', 120);
        res.setHeader('DPoP-Nonce', newNonce);
        res.status(401).json({ error: 'use_dpop_nonce' });
        return;
      }

      const consumed = await redis.del(`dpop:nonce:${nonce}`);
      if (consumed === 0) {
        const freshNonce = crypto.randomUUID();
        await redis.set(`dpop:nonce:${freshNonce}`, '1', 'EX', 120);
        res.setHeader('DPoP-Nonce', freshNonce);
        res.status(401).json({ error: 'use_dpop_nonce', error_description: 'Nonce invalid or replayed' });
        return;
      }

      // 4. Verify Access Token Hash (ath)
      const expectedAth = createHash('sha256').update(rawAccessToken, 'ascii').digest('base64url');
      if (proof.ath !== expectedAth) {
        res.status(400).json({ error: 'invalid_dpop_proof', error_description: 'ath claim mismatch' });
        return;
      }

      // 5. Verify Access Token Signature & cnf.jkt sender constraint
      const JWKS = jose.createRemoteJWKSet(new URL(`${process.env.AUTH_ISSUER_URL}/.well-known/jwks.json`));
      const { payload: tokenPayload } = await jose.jwtVerify(rawAccessToken, JWKS, {
        issuer: process.env.AUTH_ISSUER_URL,
        audience: resourceServerBaseUrl
      });

      const cnf = tokenPayload.cnf as { jkt?: string } | undefined;
      if (!cnf?.jkt || cnf.jkt !== calculatedJkt) {
        res.status(401).json({ error: 'invalid_token', error_description: 'Token sender constraint mismatch' });
        return;
      }

      req.caller = tokenPayload;
      next();
    } catch (err: unknown) {
      res.status(401).json({ error: 'invalid_token', 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: FAPI 2.0 DPoP Nonce Replay Prevention and Asymmetric Token Binding

FAPI 2.0 DPoP Nonce Replay Prevention and Asymmetric Token Binding defines an industrial-grade behavioral standard for security engineering. Enforces RFC 9449 Demonstrating Proof-of-Possession (DPoP) and FAPI 2.0 security profile invariants across OAuth 2.0 token issuance and resource access. Prevents token replay, credential theft, and man-in-the-middle attacks by mandating cryptographic key-binding of access tokens via the 'cnf.jkt' thumbprint claim and strictly validating server-supplied single-use nonces with jitter-bounded clock drift. 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 Permitting Unvalidated, Cached, or Replayed DPoP Proofs 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 Permitting Unvalidated, Cached, or Replayed DPoP ProofsCritical
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 DPoP proof JWT header contains 'typ'

Engineers MUST ALWAYS verify that the DPoP proof JWT header contains 'typ': 'dpop+jwt' and an asymmetric JWK in the 'jwk' header parameter without a private key component.

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 calculate the SHA-256 JWK thumbprint ('jkt') of the public key in the DPoP proof and match it against the 'cnf.jkt' claim embedded in the sender-constrained access token.

Engineers MUST ALWAYS calculate the SHA-256 JWK thumbprint ('jkt') of the public key in the DPoP proof and match it against the 'cnf.jkt' claim embedded in the sender-constrained 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.
3

Engineers MUST ALWAYS validate the 'htm' (HTTP method) and 'htu' (HTTP URI without query or fragment parameters) claims against the incoming HTTP request context.

Engineers MUST ALWAYS validate the 'htm' (HTTP method) and 'htu' (HTTP URI without query or fragment parameters) claims against 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.
4

Services MUST enforce server-provided 'nonce' claims in DPoP proofs, validating them against an atomic, single-use cache (e.g., Redis GETDEL) with strict TTL (<= 300 seconds) to prevent replay.

Services MUST enforce server-provided 'nonce' claims in DPoP proofs, validating them against an atomic, single-use cache (e.g., Redis GETDEL) with strict TTL (<= 300 seconds) to prevent replay.

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 reject DPoP proof timestamps ('iat') that drift beyond a 60-second window relative to server time.

Services MUST reject DPoP proof timestamps ('iat') that drift beyond a 60-second window relative to server time.

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

Components NEVER fall back to standard Bearer token authorization headers when a route or client is configured for FAPI 2.0 DPoP.

Components NEVER fall back to standard Bearer token authorization headers when a route or client is configured for FAPI 2.0 DPoP.

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

Code SHOULD verify the 'ath' (access token hash) claim in resource access DPoP proofs by computing base64url(sha256(raw_access_token)).

Code SHOULD verify the 'ath' (access token hash) claim in resource access DPoP proofs by computing base64url(sha256(raw_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.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is FAPI 2.0 DPoP Nonce Replay Prevention and Asymmetric Token Binding critical for AI coding assistants?

Enforces RFC 9449 Demonstrating Proof-of-Possession (DPoP) and FAPI 2.0 security profile invariants across OAuth 2.0 token issuance and resource access. Prevents token replay, credential theft, and man-in-the-middle attacks by mandating cryptographic key-binding of access tokens via the 'cnf.jkt' thumbprint claim and strictly validating server-supplied single-use nonces with jitter-bounded clock drift. 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 Permitting Unvalidated, Cached, or Replayed DPoP Proofs) 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

FAPI