This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: oauth2-rar-fine-grained-step-up-invariant

OAuth 2.0 RFC 9396 Rich Authorization Requests (RAR) Step-Up Enforcement

High-value and state-mutating API operations must reject coarse static OAuth 2.0 scopes and enforce RFC 9396 Rich Authorization Requests (RAR). The Resource Server must cryptographically validate authorization_details against the exact incoming transactional payload to prevent parameter tampering, authorization bypass, and cross-transaction token replay.

Prohibited Anti-Pattern: Authorizing sensitive financial or mutating operations via coarse static scopes without payload-bound authorization_details validation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OAuth 2.0 RFC 9396 Rich Authorization Requests (RAR) Step-Up Enforcement - High-value and state-mutating API operations must reject coarse static OAuth 2.0 scopes and enforce RFC 9396 Rich Authorization Requests (RAR). The Resource Server must cryptographically validate authorization_details against the exact incoming transactional payload to prevent parameter tampering, authorization bypass, and cross-transaction token replay.
globs: src/middleware/**/*.{ts,js}, src/controllers/**/*.{ts,js}, src/auth/**/*.{ts,js}, src/api/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/oauth2-rar-fine-grained-step-up-invariant"
---

# OAuth 2.0 RFC 9396 Rich Authorization Requests (RAR) Step-Up Enforcement

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Authorizing sensitive financial or mutating operations via coarse static scopes without payload-bound authorization_details validation

## System Constraints
You are a Principal Security Architect enforcing OAuth 2.0 Rich Authorization Requests (RFC 9396) and dynamic step-up authorization. Reject any implementation that uses coarse, static scopes (e.g., 'payments:write', 'admin:mutate') to authorize specific transactional mutations. Mandate fine-grained authorization_details validation, strictly asserting that token authorization parameters (target ID, action, amount, currency, recipient) strictly match the runtime request payload. When step-up or missing authorization_details are detected, mandate standard HTTP 401/403 responses containing RFC 9396 WWW-Authenticate challenge headers specifying required authorization_details.

## Strict Guidelines
- Services MUST NOT authorize sensitive or mutating operations solely by checking static string scopes (e.g., `scope.includes('transfers:write')`).
- Services MUST validate that incoming Access Tokens contain an RFC 9396 `authorization_details` claim matching the required authorization type (e.g., `type: 'customer_payment'`).
- Resource Servers MUST perform deep equality and range checks between the token's `authorization_details` parameters and the parsed HTTP request body (e.g., verifying `instructedAmount`, `currency`, and `debtorAccount` match byte-for-byte).
- Services MUST return HTTP 401/403 with `WWW-Authenticate: Bearer error="insufficient_authorization", authorization_details="..."` when step-up authorization or missing fine-grained parameters are detected.
- Access tokens containing RAR details SHOULD be sender-constrained via Demonstrating Proof-of-Possession (DPoP, RFC 9449) or Mutual-TLS (RFC 8705) to eliminate token exfiltration vectors.

## Bad vs Good Implementations
### Enforcing RFC 9396 Authorization Details vs Coarse Scopes in Step-Up Middleware

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The endpoint checks only for a coarse static scope ('transfers:write'). An attacker or compromised client can reuse a previously granted token intended for a $5 payment to authorize a $1,000,000 wire to an attacker-controlled IBAN without any payload-level cryptographic linkage.
```typescript
import { Request, Response, NextFunction } from 'express';

interface AuthenticatedRequest extends Request {
  user?: { sub: string; scopes: string[] };
}

// ANTI-PATTERN: Authorizing high-risk transfer with coarse static scopes
export async function handleTransfer(req: AuthenticatedRequest, res: Response) {
  const { amount, currency, recipientIban } = req.body;

  // Flaw: A token with 'transfers:write' can authorize any amount to any account
  if (!req.user?.scopes.includes('transfers:write')) {
    return res.status(403).json({ error: 'forbidden' });
  }

  // Parameter tampering and token replay across transactions are possible
  await executeTransfer({ amount, currency, recipientIban });
  return res.status(200).json({ status: 'success' });
}
```

#### Production Standard (Correct)
> **Standard**: The endpoint adheres to RFC 9396 by verifying the token contains explicit `authorization_details` matching the exact transactional context (amount, currency, recipient). If missing or mismatched, it issues a step-up challenge instructing the client to initiate dynamic consent for those exact parameters.
```typescript
import { Request, Response } from 'express';

interface PaymentAuthorizationDetail {
  type: 'payment_initiation';
  actions: ('initiate' | 'authorize')[];
  instructedAmount: { amount: string; currency: string };
  recipientIban: string;
}

interface RarJwtPayload {
  sub: string;
  authorization_details?: PaymentAuthorizationDetail[];
}

interface AuthenticatedRequest extends Request {
  tokenPayload?: RarJwtPayload;
}

export async function handleTransfer(req: AuthenticatedRequest, res: Response) {
  const { amount, currency, recipientIban } = req.body;

  // RFC 9396: Find matching authorization_details entry
  const authDetail = req.tokenPayload?.authorization_details?.find(
    (detail) => detail.type === 'payment_initiation' && detail.actions.includes('initiate')
  );

  // Challenge client with Step-Up RAR if missing or payload does not match token parameters
  const matchesPayload = 
    authDetail &&
    authDetail.instructedAmount.amount === String(amount) &&
    authDetail.instructedAmount.currency === currency &&
    authDetail.recipientIban === recipientIban;

  if (!matchesPayload) {
    const requiredRar = JSON.stringify([{
      type: 'payment_initiation',
      actions: ['initiate'],
      instructedAmount: { amount: String(amount), currency },
      recipientIban
    }]);

    res.setHeader(
      'WWW-Authenticate',
      `Bearer error="insufficient_authorization", error_description="Step-up RAR authorization required", authorization_details='${requiredRar}'`
    );
    return res.status(403).json({ error: 'insufficient_authorization' });
  }

  await executeTransfer({ amount, currency, recipientIban });
  return res.status(200).json({ status: 'success' });
}
```

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.0 RFC 9396 Rich Authorization Requests (RAR) Step-Up Enforcement

OAuth 2.0 RFC 9396 Rich Authorization Requests (RAR) Step-Up Enforcement defines an industrial-grade behavioral standard for security engineering. High-value and state-mutating API operations must reject coarse static OAuth 2.0 scopes and enforce RFC 9396 Rich Authorization Requests (RAR). The Resource Server must cryptographically validate authorization_details against the exact incoming transactional payload to prevent parameter tampering, authorization bypass, and cross-transaction token replay. 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: Authorizing sensitive financial or mutating operations via coarse static scopes without payload-bound authorization_details 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 DriftAuthorizing sensitive financial or mutating operations via coarse static scopes without payload-bound authorization_details 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

Services MUST NOT authorize sensitive or mutating operations solely by checking static string scopes (e.g., `scope.includes('transfers

Services MUST NOT authorize sensitive or mutating operations solely by checking static string scopes (e.g., `scope.includes('transfers:write')`).

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 validate that incoming Access Tokens contain an RFC 9396 `authorization_details` claim matching the required authorization type (e.g., `type

Services MUST validate that incoming Access Tokens contain an RFC 9396 `authorization_details` claim matching the required authorization type (e.g., `type: 'customer_payment'`).

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

Resource Servers MUST perform deep equality and range checks between the token's `authorization_details` parameters and the parsed HTTP request body (e.g., verifying `instructedAmount`, `currency`, and `debtorAccount` match byte-for-byte).

Resource Servers MUST perform deep equality and range checks between the token's `authorization_details` parameters and the parsed HTTP request body (e.g., verifying `instructedAmount`, `currency`, and `debtorAccount` match byte-for-byte).

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 return HTTP 401/403 with `WWW-Authenticate

Services MUST return HTTP 401/403 with `WWW-Authenticate: Bearer error="insufficient_authorization", authorization_details="..."` when step-up authorization or missing fine-grained parameters are detected.

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

Access tokens containing RAR details SHOULD be sender-constrained via Demonstrating Proof-of-Possession (DPoP, RFC 9449) or Mutual-TLS (RFC 8705) to eliminate token exfiltration vectors.

Access tokens containing RAR details SHOULD be sender-constrained via Demonstrating Proof-of-Possession (DPoP, RFC 9449) or Mutual-TLS (RFC 8705) to eliminate token exfiltration vectors.

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.0 RFC 9396 Rich Authorization Requests (RAR) Step-Up Enforcement critical for AI coding assistants?

High-value and state-mutating API operations must reject coarse static OAuth 2.0 scopes and enforce RFC 9396 Rich Authorization Requests (RAR). The Resource Server must cryptographically validate authorization_details against the exact incoming transactional payload to prevent parameter tampering, authorization bypass, and cross-transaction token replay. 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 (Authorizing sensitive financial or mutating operations via coarse static scopes without payload-bound authorization_details 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