This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: jwt-stateless-auth-hardening

JWT Stateless Authentication Hardening & Token Rotation Standard

Cryptographically sound JWT token architecture. Mandates asymmetric RS256/EdDSA signature verification, short-lived access tokens (15m) in HttpOnly SameSite=Strict cookies, refresh token rotation with reuse detection, and revocation blacklists.

Prohibited Anti-Pattern: AI stores tokens in localStorage (vulnerable to XSS), uses weak symmetric HS256 secrets, and allows infinite token lifespans.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: JWT Stateless Authentication Hardening & Token Rotation Standard - Cryptographically sound JWT token architecture. Mandates asymmetric RS256/EdDSA signature verification, short-lived access tokens (15m) in HttpOnly SameSite=Strict cookies, refresh token rotation with reuse detection, and revocation blacklists.
globs: **/*auth*.ts, **/*jwt*.ts, **/*session*.py
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/jwt-stateless-auth-hardening"
---

# JWT Stateless Authentication Hardening & Token Rotation Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: AI stores tokens in localStorage (vulnerable to XSS), uses weak symmetric HS256 secrets, and allows infinite token lifespans.

## System Constraints
You are an enterprise security and identity authentication engineer. Never store sensitive JWT tokens in localStorage where they are vulnerable to XSS theft. Always issue short-lived access tokens (15 minutes) and store refresh tokens in HttpOnly, Secure, SameSite=Strict cookies. Implement Refresh Token Rotation with reuse detection families to defend against token replay attacks.

## Strict Guidelines
- Store JWT tokens in HttpOnly, Secure, SameSite=Strict cookies; NEVER store tokens in localStorage, sessionStorage, or JavaScript memory.
- Keep access token expiration short (max 15 minutes); use refresh token rotation with family revocation upon reuse detection.
- Use asymmetric algorithms (RS256, ES256, or EdDSA) for signature verification; explicitly reject the 'none' algorithm and enforce strict algorithm whitelisting.
- Always maintain a fast Redis token revocation blocklist for immediate session termination upon password reset or logout.

## Bad vs Good Implementations
### HttpOnly Cookie Storage & Asymmetric RS256 vs Insecure localStorage HS256

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: localStorage is accessible to any third-party script injected via XSS, allowing attackers to exfiltrate valid 30-day tokens.
```typescript
// ANTI-PATTERN: Insecure localStorage storage and symmetric HS256
// 1. Weak hardcoded secret
const token = jwt.sign({ userId: 123 }, "my-secret-key-123", { expiresIn: "30d" });

// 2. Client stores in localStorage: A single XSS script steals the entire account!
localStorage.setItem("authToken", token);
```

#### Production Standard (Correct)
> **Standard**: HttpOnly cookies cannot be read by JavaScript even if an XSS vulnerability exists, and 15m expiration bounds exposure.
```typescript
// PRODUCTION STANDARD: Asymmetric RS256 + HttpOnly SameSite=Strict Cookie
import jwt from "jsonwebtoken";
import { Response } from "express";

export function issueAuthCookies(res: Response, userId: string, privateKeyPem: string) {
  // 1. Short-lived Access Token (15 minutes) signed with asymmetric RS256
  const accessToken = jwt.sign(
    { sub: userId, type: "access" },
    privateKeyPem,
    { algorithm: "RS256", expiresIn: "15m", issuer: "auth.acme.com" }
  );

  // 2. Store in secure, HttpOnly cookie (inaccessible to client JavaScript/XSS)
  res.cookie("access_token", accessToken, {
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
    sameSite: "strict",
    maxAge: 15 * 60 * 1000, // 15 minutes
    path: "/",
  });
}
```

### Refresh Token Rotation with Reuse Detection

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: If an attacker captures the refresh token once, they maintain permanent unauthorized access.
```typescript
// ANTI-PATTERN: Static refresh token that never changes
async function refresh(oldToken) {
  return generateAccessToken(oldToken.userId); // Infinite token replay!
}
```

#### Production Standard (Correct)
> **Standard**: Detects token theft automatically: if a used token is replayed, the entire family is invalidated immediately.
```typescript
// PRODUCTION STANDARD: Token Family Invalidation on Reuse
async function rotateRefreshToken(tokenFamilyId: string, presentedTokenHash: string, db: any) {
  const record = await db.refreshToken.findUnique({ where: { hash: presentedTokenHash } });
  
  if (!record || record.isRevoked) {
    // REUSE DETECTED: Compromise! Revoke entire token family immediately!
    await db.refreshToken.updateMany({
      where: { familyId: tokenFamilyId },
      data: { isRevoked: true },
    });
    throw new Error("Security Alert: Reused token detected, all sessions revoked.");
  }

  // Issue brand-new refresh token and invalidate old one
  await db.refreshToken.update({ where: { id: record.id }, data: { isRevoked: true } });
  return issueNewTokenInFamily(tokenFamilyId);
}
```

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: JWT Stateless Authentication Hardening & Token Rotation Standard

JWT Stateless Authentication Hardening & Token Rotation Standard defines an industrial-grade behavioral standard for security engineering. Cryptographically sound JWT token architecture. Mandates asymmetric RS256/EdDSA signature verification, short-lived access tokens (15m) in HttpOnly SameSite=Strict cookies, refresh token rotation with reuse detection, and revocation blacklists. 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: AI stores tokens in localStorage (vulnerable to XSS), uses weak symmetric HS256 secrets, and allows infinite token lifespans. 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 DriftAI stores tokens in localStorage (vulnerable to XSS), uses weak symmetric HS256 secrets, and allows infinite token lifespans.Critical
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

Store JWT tokens in HttpOnly, Secure, SameSite=Strict cookies

Store JWT tokens in HttpOnly, Secure, SameSite=Strict cookies; NEVER store tokens in localStorage, sessionStorage, or JavaScript memory.

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

Keep access token expiration short (max 15 minutes)

Keep access token expiration short (max 15 minutes); use refresh token rotation with family revocation upon reuse detection.

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

Use asymmetric algorithms (RS256, ES256, or EdDSA) for signature verification

Use asymmetric algorithms (RS256, ES256, or EdDSA) for signature verification; explicitly reject the 'none' algorithm and enforce strict algorithm whitelisting.

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

Always maintain a fast Redis token revocation blocklist for immediate session termination upon password reset or logout.

Always maintain a fast Redis token revocation blocklist for immediate session termination upon password reset or logout.

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 JWT Stateless Authentication Hardening & Token Rotation Standard critical for AI coding assistants?

Cryptographically sound JWT token architecture. Mandates asymmetric RS256/EdDSA signature verification, short-lived access tokens (15m) in HttpOnly SameSite=Strict cookies, refresh token rotation with reuse detection, and revocation blacklists. 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 (AI stores tokens in localStorage (vulnerable to XSS), uses weak symmetric HS256 secrets, and allows infinite token lifespans.) 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

JWT