Auth Operations

SkillCloud & infra

Authentication and authorization patterns - JWT, OAuth2, sessions, RBAC, ABAC, passkeys, MFA, identity-aware proxies, and Better Auth. Use for: authentication, jwt, oauth2, session, login, rbac, abac, passkey, mfa, totp, api key, token, cookie, csrf, bearer token, refresh token, oidc, cloudflare access, zero trust, Cf-Access-Jwt-Assertion, AUD tag, service auth, better auth.

Available today. Use it from your connected AI after setup.

Connect ahel once, and every AI you use reads what you have installed.

Then ask your AI: use the Auth Operations skill

What this skill tells your AI

The instructions your AI receives, as published by 0xdarkmatter/claude-mods in skills/auth-ops/SKILL.md and read by ahel’s review.

Comprehensive authentication and authorization patterns for secure application development across languages and frameworks.

Authentication Method Decision Tree

Use this tree to select the right authentication strategy for your use case.

What are you building?
│
├─ Traditional web application (server-rendered)?
│  └─ Session-based authentication
│     ├─ Server stores session data (Redis/DB)
│     ├─ Session ID in httpOnly cookie
│     └─ Best for: monoliths, SSR apps, admin panels
│
├─ API consumed by multiple clients?
│  └─ JWT (JSON Web Tokens)
│     ├─ Stateless, self-contained tokens
│     ├─ Access token (short-lived) + refresh token (long-lived)
│     └─ Best for: microservices, mobile apps, SPAs via BFF
│
├─ Service-to-service communication?
│  └─ API keys or Client Credentials (OAuth2)
│     ├─ API keys: simple, scoped, rotatable
│     ├─ Client Credentials: OAuth2 standard, token-based
│     └─ Best for: internal services, third-party integrations
│
├─ Third-party login (Google, GitHub, etc.)?
│  └─ OAuth2 / OpenID Connect
│     ├─ Authorization Code + PKCE for web/mobile
│     ├─ Delegate identity to trusted providers
│     └─ Best for: consumer apps, social login
│
├─ Passwordless authentication?
│  └─ Passkeys (WebAuthn) or Magic Links
│     ├─ Passkeys: phishing-resistant, biometric/hardware
│     ├─ Magic links: email-based, time-limited
│     └─ Best for: high-security, modern UX
│
└─ Internal tool / staff app with an existing IdP?
   └─ Identity-aware proxy (Cloudflare Access)
      ├─ Authn enforced at the edge, before your origin
      ├─ Origin verifies the proxy's signed JWT (never a bare header)
      └─ Best for: admin panels, partner portals, not consumer signup

JWT Quick Reference

Structure

Header.Payload.Signature

Header:  { "alg": "RS256", "typ": "JWT" }
Payload: { "iss": "auth.example.com", "sub": "user_123", ... }
Signature: RSASHA256(base64(header) + "." + base64(payload), privateKey)

Common Claims

ClaimNamePurposeExample
issIssuerWho issued the token"auth.example.com"
subSubjectWho the token represents"user_123"
expExpirationWhen the token expires1700000000 (Unix timestamp)
iatIssued AtWhen the token was created1699999100
audAudienceIntended recipient(s)"api.example.com"
jtiJWT IDUnique token identifier"a1b2c3d4" (for revocation)
nbfNot BeforeToken not valid before this time1699999100

Signing Algorithms

AlgorithmTypeKeyUse When
RS256Asymmetric (RSA)Public/private key pairDistributed systems, multiple verifiers
ES256Asymmetric (ECDSA)Public/private key pairSame as RS256, smaller keys/signatures
HS256Symmetric (HMAC)Shared secretSingle service, simple setups

Rule of thumb: Use asymmetric (RS256/ES256) when the token issuer and verifier are different services. Use HS256 only when a single service both creates and verifies tokens.

Access + Refresh Token Pattern

┌──────────┐                    ┌──────────┐
│  Client   │─── login ────────>│  Auth    │
│           │<── access (15m) ──│  Server  │
│           │<── refresh (7d) ──│          │
│           │                   └──────────┘
│           │─── API call ─────>┌──────────┐
│           │    (access token) │ Resource │
│           │<── response ──────│  Server  │
│           │                   └──────────┘
│           │─── access expired │          │
│           │─── refresh ──────>│  Auth    │
│           │<── new access ────│  Server  │
│           │<── new refresh ───│  (rotate)│
└──────────┘                    └──────────┘
  • Access token: Short-lived (5-15 minutes), used for API calls
  • Refresh token: Long-lived (7-30 days), used to get new access tokens
  • Rotation: Issue a new refresh token with each use, invalidate the old one
  • Family detection: Track refresh token lineage; if a revoked token is reused, invalidate the entire family

OAuth2 Flow Decision Tree

What type of client?
│
├─ Web app with backend (Next.js, Rails, Django)?
│  └─ Authorization Code + PKCE
│     ├─ Redirect user to authorization server
│     ├─ Receive code at callback URL
│     ├─ Exchange code for tokens server-side
│     └─ PKCE prevents code interception attacks
│
├─ SPA (React, Vue) without backend?
│  └─ Authorization Code + PKCE (via BFF)
│     ├─ Use a Backend-for-Frontend to handle tokens
│     ├─ Never store tokens in browser-accessible storage
│     └─ BFF proxies API calls with token attached
│
├─ Mobile app (iOS, Android)?
│  └─ Authorization Code + PKCE
│     ├─ Use custom URI scheme or universal links for redirect
│     ├─ PKCE is mandatory (public client)
│     └─ Store tokens in secure enclave/keystore
│
├─ Server-to-server (no user)?
│  └─ Client Credentials
│     ├─ Authenticate with client_id + client_secret
│     ├─ No user context, service-level access
│     └─ Token cached until expiry
│
├─ CLI tool or smart TV?
│  └─ Device Code
│     ├─ Display code and URL to user
│     ├─ User authenticates on another device
│     ├─ CLI/TV polls for completion
│     └─ Good UX for input-constrained devices
│
└─ Microservice acting on behalf of a user?
   └─ Token Exchange (RFC 8693)
      ├─ Exchange user's token for a scoped downstream token
      ├─ Maintains user context across services
      └─ Use `act` claim for delegation chain

Authorization Model Decision Tree

How complex are your access control needs?
│
├─ Simple: just "can user X do action Y"?
│  └─ Permission-based (direct)
│     ├─ user_permissions table
│     ├─ Simple to implement, hard to scale
│     └─ Good for: small apps, prototypes
│
├─ Users grouped into roles with fixed permissions?
│  └─ RBAC (Role-Based Access Control)
│     ├─ Roles: admin, editor, viewer
│     ├─ Each role has a set of permissions
│     ├─ Users assigned one or more roles
│     └─ Good for: most apps, admin panels, team tools
│
├─ Decisions depend on attributes (time, location, resource owner)?
│  └─ ABAC (Attribute-Based Access Control)
│     ├─ Policies evaluate subject + resource + environment attributes
│     ├─ "Allow if user.department == resource.department AND time < 17:00"
│     ├─ Flexible but complex
│     └─ Good for: enterprise, compliance-heavy, context-dependent access
│
└─ Access based on relationships (owner, parent, shared with)?
   └─ ReBAC (Relationship-Based Access Control)
      ├─ Google Zanzibar model
      ├─ Tuples: user:alice#viewer@document:report
      ├─ Supports inheritance: folder viewer → document viewer
      ├─ Tools: OpenFGA, SpiceDB, Ory Keto
      └─ Good for: file sharing, nested resources, social features

Session Management Quick Reference

Cookie Security Settings

SettingValuePurpose
SameSiteStrictCookie sent only for same-site requests (best CSRF protection)
SameSiteLaxCookie sent for top-level navigations (good default)
SameSiteNoneCookie sent for cross-site requests (requires Secure)
SecuretrueCookie only sent over HTTPS
HttpOnlytrueCookie not accessible via JavaScript (prevents XSS theft)
__Host- prefixN/ARequires Secure, no Domain, Path=/ (strictest)
__Secure- prefixN/ARequires Secure flag
Max-AgesecondsCookie lifetime (prefer over Expires)
Path/Scope cookie to path (usually /)

Recommended Cookie Configuration

Set-Cookie: __Host-session=abc123;
  Secure;
  HttpOnly;
  SameSite=Lax;
  Max-Age=86400;
  Path=/

Session Expiry Strategies

StrategyTypical ValueNotes
Idle timeout15-30 minutesReset on each request
Absolute timeout8-24 hoursForce re-authentication
Sliding window30 min idle, 8h maxBest balance
Remember me30 daysExtended session, reduced privileges

Password Handling Quick Reference

Hashing Algorithms

AlgorithmVerdictNotes
argon2idBESTMemory-hard, resists GPU attacks, recommended by OWASP
bcryptGOODBattle-tested, cost factor 12+, 72-byte input limit
scryptGOODMemory-hard, less common library support
PBKDF2ACCEPTABLEFIPS compliant, use 600k+ iterations with SHA-256
SHA-256/512BADToo fast, no salt built-in, easily brute-forced
MD5NEVERBroken, rainbow tables widely available

Password Rules (NIST 800-63B)

RuleGuidance
Minimum length8 characters (12+ recommended)
Maximum lengthAt least 64 characters
Complexity rulesDo NOT require special chars/uppercase/numbers
Breached password checkCheck against known breached passwords (HaveIBeenPwned API)
Password hintsDo NOT allow
Forced rotationDo NOT force periodic changes (only on breach)
Paste into password fieldALLOW (supports password managers)

Rate Limiting Login Attempts

AttemptResponse
1-5Normal login
6-10CAPTCHA required
11-20Progressive delays (2s, 4s, 8s...)
20+Temporary account lockout (15-30 min)

Important: Use consistent response times for both success and failure to prevent timing-based username enumeration.

MFA Quick Reference

Methods Ranked by Security

MethodSecurityUXNotes
WebAuthn/PasskeysHighestGoodPhishing-resistant, hardware-backed
TOTP (Authenticator)HighMediumApp-based (Google/Microsoft Authenticator)
Push notificationsHighGoodRequires mobile app
Email OTPMediumMediumDepends on email security
SMS OTPLowEasySIM swap vulnerable, use as fallback only

TOTP Implementation Checklist

  • Generate 160-bit secret (base32 encoded)
  • Build otpauth:// URI with issuer and account
  • Display QR code for authenticator scanning
  • Require verification of first code before enabling
  • Accept current window +/- 1 (30-second steps)
  • Generate 8-10 single-use backup codes
  • Hash backup codes before storing
  • Allow recovery via verified identity

Passkey/WebAuthn Checklist

  • Generate cryptographic challenge on server
  • Set relying party ID (your domain)
  • Store credential public key and ID
  • Verify signature on authentication
  • Support multiple credentials per user
  • Handle platform vs cross-platform authenticators
  • Provide fallback auth method

Identity-Aware Proxy Quick Reference

When authn is delegated to a proxy edge (Cloudflare Access, Google IAP, oauth2-proxy), two invariants carry the whole model:

  1. Verify the assertion. The proxy's identity header is a signed JWT — verify signature + issuer + per-application audience against the proxy's JWKS on every request. Never trust the plain email convenience headers.
  2. Close every path around the proxy. The header is only meaningful if the proxy is the only way to reach the origin (workers_dev = false, firewalled origin, or tunnel). An open origin makes any header forgeable.
Proxy edge (authn) ──JWT header──> Origin verifies JWT ──> app user lookup ──> role/scope binding
     │                                  │ 403 on any failure     │ 403 if no row     (server-side)
     └ IdP / OTP login, sessions        └ cached JWKS,           └ proxy admits ≠ app authorizes
       rate limits, bot defense           refetch on unknown kid

Machine routes (webhooks, ingest) get Service-Auth/Bypass at the edge + bearer keys at the origin, mounted outside the human-auth middleware. Full treatment: references/cloudflare-access.md.

Common Gotchas

GotchaWhy It's DangerousFix
JWT stored in localStorageXSS can steal tokens, no expiry enforcement by browserUse httpOnly cookies or BFF pattern
Missing PKCE in OAuth2Authorization code interception attacks possibleAlways use PKCE, even for confidential clients
Role explosion in RBACHundreds of roles become unmanageableMove to ABAC or ReBAC for complex scenarios
String comparison for tokensTiming attacks reveal token value character by characterUse constant-time comparison (crypto.timingSafeEqual)
No token revocation strategyCannot invalidate compromised JWTs before expiryShort expiry + refresh tokens, or maintain a blocklist
CORS with credentials: trueAccess-Control-Allow-Origin: * does not work with credentialsSpecify exact origin, set Access-Control-Allow-Credentials: true
SameSite=None without SecureBrowser silently rejects the cookieAlways pair SameSite=None with Secure flag
Refresh token reuse without detectionStolen refresh tokens grant indefinite accessRotate refresh tokens, detect reuse (token families)
Using OAuth2 Implicit grantTokens exposed in URL fragment, no refresh tokensUse Authorization Code + PKCE instead (Implicit is deprecated)
Password in URL or logsURLs are logged by proxies, browsers, and serversAlways send credentials in request body or headers
Missing CSRF protection with cookiesCookie-based auth is vulnerable to cross-site request forgeryUse SameSite cookies + CSRF tokens for state-changing ops
Long-lived access tokens (hours/days)Large attack window if token is compromisedKeep access tokens to 5-15 minutes, use refresh tokens
Storing API keys in plaintextDatabase breach exposes all keysHash stored keys (SHA-256 of key), store prefix for lookup
Not validating JWT aud claimToken meant for Service A accepted by Service BAlways validate aud matches your service identifier
Session fixationAttacker sets session ID before login, then hijacks itRegenerate session ID after authentication
Hardcoded secrets in codeSecrets leak via source controlUse environment variables or secret managers (Vault, AWS SSM)
Trusting an identity-aware proxy's plain email headerHeaders are attacker-settable on any unproxied pathVerify the proxy's signed JWT (sig + issuer + audience); close every path around the proxy
Auth-library middleware as the only session checkFramework middleware can be bypassed (Next.js CVE-2025-29927 class)Re-check the session in the data-access layer / route handlers

Reference Files

FileContentsLines
references/jwt-sessions.mdJWT structure, signing, sessions, cookies, CSRF, storage~650
references/oauth2-oidc.mdOAuth2 flows, OIDC, provider integration, social login~700
references/authorization.mdRBAC, ABAC, ReBAC, RLS, multi-tenant, audit logging~600
references/implementation.mdPassword hashing, MFA, rate limiting, API keys, reset flows~550
references/cloudflare-access.mdIdentity-aware proxies via Cloudflare Access: app/policy anatomy, token claims, JWT verification, closed-origin precondition, service auth, sessions/logout/SPA, local dev~330
references/better-auth.mdBetter Auth library: server/client setup, adapters, session model, social login, plugin catalog (passkey/2FA/org/SSO), Hono integration, migration~240

See Also

  • security-ops - Broader security patterns: OWASP, headers, input validation, encryption
  • api-design-ops - API design including authentication endpoints, rate limiting
  • postgres-ops - Row-level security (RLS) policies for database authorization
  • cloudflare-ops - Workers runtime, wrangler config, secrets, deploy mechanics behind an Access-fronted origin

Signals

GitHub stars
36
Forks
5
Last commit
Aug 2026
Advanced
Catalog kind
skill
Gateway key
auth-ops
Source
github.com/0xdarkmatter/claude-mods