Authentication patterns

From FerroxLabs/murage · View interactive version

Authentication patterns is an AI agent skill from the GitHub repository FerroxLabs/murage. Guides expert-level authentication patterns implementation: security and web-development decision frameworks, production-ready patterns, and concrete templates for authentication patterns workflows. Use when the user asks about authentication patterns, authentication patterns configuration, or secur

How to use this skill

Skill file

Authentication Patterns

When to Use

Use this skill when:

Do NOT use this skill when:


Process

1. Classify the Authentication Context

Before recommending any pattern, establish which category of authentication the user actually needs. These have fundamentally different solutions.

Identify which category applies -- or if the system must support multiple categories simultaneously. A SaaS product commonly needs H2M for end users AND M2M for its own backend services AND enterprise SSO for enterprise customers.

2. Map Requirements to the Authentication Decision Matrix

Collect the following constraints explicitly from the user before recommending a pattern:

3. Select the Core Authentication Pattern

Use this decision tree:

If the client is a traditional server-rendered web app (Rails, Django, Laravel, Express with server-side templates):

-- Use server-side sessions with HttpOnly, Secure, SameSite=Strict cookies. Store session data in Redis or a database. This is the simplest, most secure pattern for this context.

If the client is a SPA (React, Vue, Angular) or mobile app:

-- Use OAuth 2.0 Authorization Code flow with PKCE. Issue short-lived access tokens (15 minutes) and rotate refresh tokens on every use (rolling refresh token rotation). Store access tokens in memory (not localStorage). Store refresh tokens in HttpOnly cookies or platform secure storage.

If the API is consumed by trusted backend services you control:

-- Use OAuth 2.0 Client Credentials flow. Issue long-lived client secrets stored in a vault (never in code). Rotate secrets on a schedule (90-day maximum) or immediately on suspected compromise.

If you need enterprise SSO:

-- Implement OpenID Connect (OIDC) as the primary protocol; add SAML 2.0 support for enterprises that mandate it. OIDC is preferred -- SAML is XML-based, complex, and has a larger attack surface. Use a library (passport-saml, python-saml3, Spring Security SAML) rather than writing a parser.

If you want passwordless:

-- WebAuthn/FIDO2 (passkeys) is the most secure option. Magic links are acceptable for low-sensitivity apps. TOTP via authenticator app is a reasonable middle ground when passkeys can't be mandated.

4. Design the Token and Session Architecture

The implementation details that separate production-ready auth from toy implementations:

JWT (JSON Web Tokens):

Session cookies:

Refresh token rotation:

5. Implement Credential Handling and Password Storage

Password storage is a solved problem -- use the right algorithm and nothing else.

Password hashing algorithm selection (2024 guidance):

Credential validation during login:

Credential stuffing protection:

6. Implement Multi-Factor Authentication (MFA)

MFA should be designed as a first-class feature, not bolted on. Plan the enrollment flow, recovery flow, and bypass policies from the start.

Second factor options by security tier:

| Factor | Security | UX | Phishing Resistant | Notes |

|--------|----------|----|--------------------|-------|

| WebAuthn/Passkey | Very High | High | Yes | Best option when usable |

| TOTP (Authenticator app) | High | Medium | No | TOTP codes can be phished in real time |

| SMS OTP | Medium | High | No | SIM-swap attack vector; avoid for high-security |

| Email OTP | Medium | High | No | Acceptable when email account is itself secured |

| Push notification | High | Very High | Partial | Requires proprietary app or Duo/Okta |

| Hardware key (FIDO2) | Very High | Medium | Yes | Best for privileged accounts |

TOTP implementation specifics:

MFA enrollment UX:

7. Implement Security Headers, Logging, and Monitoring

Authentication without observability is incomplete. These are required, not optional.

Security headers for auth endpoints:

Audit logging -- every auth event must be logged:

Alerting thresholds:

8. Validate and Harden the Implementation

Run through this checklist before marking authentication work as production-ready:


Output Format

When responding to an authentication patterns question, structure output as follows:

## Authentication Pattern Recommendation: [Context Summary]

### Context Classification
- Auth type: [H2M / M2M / Third-party delegated / Enterprise SSO / Passwordless]
- Client type: [Traditional web / SPA / Mobile / CLI / Service]
- Key constraints: [Stateless requirement / Revocation needs / Compliance / Scale]

### Pattern Decision Matrix

| Criterion            | Session Cookies | JWT + Refresh | OAuth PKCE | API Key |
|----------------------|-----------------|---------------|------------|---------|
| Stateless scaling    | Poor            | Good          | Good       | Good    |
| Immediate revocation | Excellent       | Poor*         | Poor*      | Good    |
| Browser security     | Excellent       | Medium        | Medium     | Poor    |
| Mobile support       | Poor            | Excellent     | Excellent  | Good    |
| Implementation complexity | Low       | Medium        | High       | Low     |
| Compliance (MFA, audit) | Good        | Good          | Good       | Limited |

*Can be improved with jti deny-list at cost of a Redis lookup per request

### Recommended Pattern
[Specific pattern name and rationale tied to the user's constraints]

### Token/Session Architecture

**Access Token:**
- Type: [JWT RS256 / Opaque / Session ID]
- TTL: [X minutes]
- Storage: [Memory / HttpOnly cookie / Secure Enclave]
- Payload fields: [sub, iat, exp, jti, ...]

**Refresh Token (if applicable):**
- TTL: [X days]
- Rotation: [Rolling / Absolute]
- Storage: [HttpOnly cookie / Keychain / Database hash]
- Revocation: [Token family invalidation on reuse]

### Password/Credential Handling
- Hashing: [Argon2id / bcrypt / scrypt] with [parameters]
- Pepper: [Yes/No, vault location]
- Breach check: [HIBP k-anonymity / not applicable]

### MFA Strategy
- Required for: [All users / Admin users / Configurable per user]
- Supported factors: [TOTP / WebAuthn / SMS / Email OTP]
- Recovery: [N backup codes, single-use, hashed at rest]

### Implementation Sketch

\`\`\`[language]
[Concrete, runnable code demonstrating the core auth flow]
\`\`\`

### Security Checklist
- [ ] [Item specific to recommended pattern]
- [ ] [Item specific to recommended pattern]
... (all applicable items from Step 8)

### Known Trade-offs
[Explicit acknowledgment of what the recommended approach gives up and why it is still the right choice]

Rules

  1. NEVER store JWT access tokens in localStorage or sessionStorage. These are accessible to any JavaScript running on the page, making them vulnerable to XSS. If you cannot use HttpOnly cookies (e.g., cross-origin API), store access tokens in memory (JavaScript variable) and refresh tokens in HttpOnly cookies or platform secure storage.
  1. NEVER implement your own cryptographic primitives. Use libsodium, bcrypt, argon2, or your language's standard crypto library. The phrase "I'll roll my own HMAC" is a red flag. The only custom crypto is parameter selection.
  1. NEVER issue a JWT without an expiration (exp claim). A JWT without exp is valid forever unless explicitly revoked, which requires the stateful infrastructure that JWT was meant to avoid.
  1. ALWAYS rotate the session ID after a successful login. Failure to do so enables session fixation attacks, where an attacker pre-plants a known session ID and then waits for the victim to authenticate, inheriting their session.
  1. NEVER use MD5 or SHA-1 for password hashing -- or any hash function not designed as a password KDF. General-purpose hash functions are too fast; an attacker with a GPU cluster can attempt billions of SHA-256 hashes per second. Argon2id is designed to be slow and memory-hard.
  1. ALWAYS treat a "reused refresh token" event as a security incident. Under rolling refresh token rotation, a previously issued refresh token should never be presented again. If it is, either the original token was stolen or the client has a bug. Either way, invalidate the entire token family immediately and notify the user.
  1. NEVER include sensitive data in the JWT payload. The payload is base64url-encoded -- it is not encrypted. Anyone who intercepts the token can read all claims. Keep only non-sensitive identifiers. If you need to transmit sensitive data, use JWE (JSON Web Encryption) instead.
  1. ALWAYS use PKCE (Proof Key for Code Exchange) for Authorization Code flow in public clients. This includes SPAs and native mobile apps. Without PKCE, an authorization code intercepted in transit (via URL redirect sniffing or redirect URI misconfiguration) can be exchanged for tokens by an attacker.
  1. NEVER allow the "forgot password" token to be reusable or long-lived. Password reset tokens must be: single-use (invalidate on first use), time-limited (15--60 minutes maximum), cryptographically random (128+ bits), and stored as a hash server-side. Sending a raw token in a URL is standard; storing it raw in the database is not.
  1. ALWAYS enforce MFA for privileged accounts regardless of user preference. Standard users may have MFA optional or strongly recommended, but accounts with admin rights, infrastructure access, or access to PII must have MFA enforced at the policy level. "The admin disabled their own MFA for convenience" is a common precursor to serious incidents.

Edge Cases

Handling Token Refresh Race Conditions in SPAs

When a SPA makes concurrent API requests and the access token expires mid-flight, multiple requests will simultaneously attempt to refresh the token. Without coordination, this generates multiple refresh requests, and all but the first will fail (since the refresh token is rotated). Solve this with a refresh lock: use a Promise-based singleton in the frontend that queues concurrent refresh attempts behind a single in-flight refresh call. All waiters receive the same new token. In practice this means holding a refreshPromise variable -- if it is null, start the refresh and assign the promise; if it is already set, return the existing promise. Release the lock only after the new token is stored.

Implementing Auth in Multi-Tenant SaaS

Each tenant may have different auth requirements: one tenant uses social login, another requires SAML SSO with their corporate IdP, a third enforces TOTP MFA. Model this with a per-tenant auth configuration table that specifies: allowed authentication methods, required MFA level, session timeout override, and IdP connection details. At login, resolve the user's tenant first (via email domain, subdomain, or explicit tenant selection), then apply that tenant's auth policy. Ensure that a token issued in Tenant A can never be used to access Tenant B's resources -- include a tenant_id claim in the JWT and validate it against the requested resource on every API call.

Social Login Account Linking

A user may sign up with Google, then later try to log in with GitHub using the same email address. Do NOT automatically merge these accounts -- this is a common account takeover vector (an attacker registers a GitHub account with the victim's email). Instead: if the email is already registered via a different method, prompt the user to log in with their existing method first, then offer to link the social account from settings. Only link accounts when the user is already authenticated. Always verify that the OAuth provider has confirmed the email address (email_verified: true in OIDC claims).

Migrating Password Hashes to a Stronger Algorithm

When inheriting a legacy system using MD5 or SHA-1 hashes, you cannot bulk-rehash without knowing plaintext passwords. Use an on-login migration: when a user successfully authenticates with the old algorithm, immediately rehash their plaintext password using Argon2id and store the new hash alongside a flag indicating the new algorithm. Expire the old hash. Add a column hash_algorithm or a version prefix to each stored hash. Over time, as users log in, the database migrates organically. Force-expire any remaining old-format hashes after 90--180 days and require a password reset for users who have not logged in within that window.

WebAuthn/Passkey Implementation Pitfalls

WebAuthn challenges must be cryptographically random (128 bits minimum), generated server-side, stored in session, and consumed within 60--120 seconds. Never allow challenge reuse. The rpId (relying party ID) must match the effective domain -- if your app is app.example.com, the rpId can be app.example.com or example.com but not example.com.attacker.com. Verify the origin in the authenticator data against your expected origin -- this prevents cross-origin credential use. For account recovery when a user loses their passkey, provide backup codes generated at passkey enrollment, and optionally allow a secondary passkey to be registered. Do not fall back to SMS OTP alone as it downgrades the security level.

Logout and Token Invalidation

True logout in a JWT-stateless system requires effort. Clearing the client-side token is not sufficient -- an attacker who has already exfiltrated the token can still use it until it expires. Implement logout as: (1) invalidate the refresh token in the database immediately, (2) add the access token's jti to a Redis deny-list with TTL equal to the remaining access token lifetime, (3) clear all cookies client-side, (4) redirect to the authorization server's logout endpoint if using OIDC (to clear the IdP session). For high-security applications, reduce access token TTL to 5 minutes so the deny-list TTL is negligible.

Machine-to-Machine Service Authentication in Kubernetes

In a Kubernetes environment, prefer workload identity over long-lived API keys. Use service account tokens projected into pods (short-lived, automatically rotated by the Kubernetes control plane), or use a service mesh (Istio, Linkerd) with mutual TLS (mTLS) for service-to-service authentication. If using OAuth 2.0 Client Credentials for M2M, store the client secret in Kubernetes Secrets encrypted at rest, or better, in an external vault with the Vault Agent sidecar or CSI driver injecting the secret at pod startup. Never mount secrets as environment variables in Kubernetes -- use file-based secret mounts so secrets are not exposed in process listings or crash dumps.


Example

Input: "I'm building a React SPA with a Node.js/Express API. Users log in with email and password, and we're adding Google sign-in. We need to support MFA. The API is consumed only by our own frontend -- no third-party API access. We have Redis available. What authentication pattern should I use?"


Output:

Authentication Pattern Recommendation: React SPA + Express API, Email/Password + Google SSO, MFA

Context Classification

Pattern Decision Matrix

| Criterion | Session Cookies | JWT (memory) + HttpOnly Refresh Cookie | localStorage JWT |

|-----------|-----------------|----------------------------------------|-----------------|

| XSS token theft | Excellent (HttpOnly) | Excellent (memory) | Poor (exposed) |

| CSRF risk | Medium (mitigated by SameSite) | Low | Low |

| Revocation | Excellent | Good (jti deny-list + refresh revoke) | Poor |

| Horizontal scale (Redis) | Excellent | Good | Good |

| SPA compatibility | Good | Excellent | Works (but avoid) |

| Google SSO integration | Good | Excellent | Works (but avoid) |

Recommended Pattern

OAuth 2.0 Authorization Code + PKCE for Google SSO, with short-lived JWTs (access tokens in memory, refresh tokens in HttpOnly cookies), backed by Redis for session metadata and token revocation.

Rationale: A pure session-cookie approach works for first-party SPAs, but JWT + refresh tokens integrate more cleanly with the Google OIDC flow, handle token refresh races more elegantly in React (via interceptor pattern), and scale horizontally without session affinity. With Redis available, immediate revocation via jti deny-list is trivial to implement.


Token Architecture

Access Token:

Refresh Token:

Google SSO Token Handling:


Password/Credential Handling

// server/auth/password.js
import argon2 from 'argon2';
import crypto from 'crypto';

const PEPPER = process.env.PASSWORD_PEPPER; // 32-byte hex string from vault

const ARGON2_OPTIONS = {
  type: argon2.argon2id,
  memoryCost: 65536,    // 64 MB
  timeCost: 3,          // 3 iterations
  parallelism: 2,
  hashLength: 32,
};

export async function hashPassword(plaintext) {
  // Apply pepper before hashing -- pepper is not stored in DB
  const peppered = crypto
    .createHmac('sha256', PEPPER)
    .update(plaintext)
    .digest('hex');
  return argon2.hash(peppered, ARGON2_OPTIONS);
}

export async function verifyPassword(plaintext, storedHash) {
  const peppered = crypto
    .createHmac('sha256', PEPPER)
    .update(plaintext)
    .digest('hex');
  return argon2.verify(storedHash, peppered);
}

Breach check on registration/password change -- call HIBP k-anonymity API:

import crypto from 'crypto';

export async function isPasswordBreached(password) {
  const sha1 = crypto.createHash('sha1').update(password).digest('hex').toUpperCase();
  const prefix = sha1.slice(0, 5);
  const suffix = sha1.slice(5);
  const response = await fetch(`https://api.pwnedpasswords.com/range/${prefix}`);
  const text = await response.text();
  return text.split('\n').some(line => line.startsWith(suffix));
}

Login Flow Implementation

// server/routes/auth.js
import { Router } from 'express';
import { verifyPassword } from '../auth/password.js';
import { issueTokens, revokeTokenFamily } from '../auth/tokens.js';
import { getUserByEmail } from '../db/users.js';
import rateLimit from 'express-rate-limit';
import crypto from 'crypto';

const loginLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 10,                   // 10 attempts per IP per window
  keyGenerator: (req) => req.body.email || req.ip, // per-account limiting
  skipSuccessfulRequests: true,
});

router.post('/login', loginLimiter, async (req, res) => {
  const { email, password } = req.body;
  const user = await getUserByEmail(email);

  // Use constant-time path -- always verify even if user not found (prevents user enumeration)
  const dummyHash = '$argon2id$v=19$m=65536,t=3,p=2$...'; // precomputed dummy
  const validPassword = user
    ? await verifyPassword(password, user.passwordHash)
    : await verifyPassword(password, dummyHash) && false; // always false for nonexistent user

  if (!user || !validPassword) {
    // Do NOT distinguish "wrong password" from "no such user" in the response
    return res.status(401).json({ error: 'Invalid credentials' });
  }

  if (user.mfaEnabled) {
    // Issue a short-lived, single-purpose pre-auth token (5 minute TTL)
    // Do not issue full tokens yet -- MFA not yet verified
    const preAuthToken = crypto.randomBytes(32).toString('hex');
    await redis.setex(`preauth:${preAuthToken}`, 300, user.id);
    return res.json({ requiresMfa: true, preAuthToken });
  }

  // Regenerate session -- no old session to fixate on for JWT approach,
  // but clear any existing refresh cookie before issuing new one
  const { accessToken, refreshToken } = await issueTokens(user.id);

  res.cookie('refreshToken', refreshToken, {
    httpOnly: true,
    secure: true,
    sameSite: 'lax',
    maxAge: 7 * 24 * 60 * 60 * 1000, // 7 days
    path: '/auth/refresh',             // Scope cookie to refresh endpoint only
  });

  res.json({ accessToken });
});

MFA Implementation (TOTP)

// server/auth/totp.js
import * as OTPAuth from 'otpauth';
import crypto from 'crypto';
import QRCode from 'qrcode';

export function generateTOTPSecret() {
  return crypto.randomBytes(20).toString('base64').replace(/[^A-Z2-7]/gi, 'A').toUpperCase();
}

export async function generateEnrollmentQR(user, secret) {
  const totp = new OTPAuth.TOTP({
    issuer: 'YourAppName',
    label: user.email,
    algorithm: 'SHA1',
    digits: 6,
    period: 30,
    secret: OTPAuth.Secret.fromBase32(secret),
  });
  return QRCode.toDataURL(totp.toString());
}

export function verifyTOTP(secret, token, redis) {
  const totp = new OTPAuth.TOTP({
    secret: OTPAuth.Secret.fromBase32(secret),
    algorithm: 'SHA1',
    digits: 6,
    period: 30,
  });

  // Window of 1 = accept t-1, t, t+1 (accounts for clock skew)
  const delta = totp.validate({ token, window: 1 });
  if (delta === null) return false;

  // Prevent replay: store used token in Redis with TTL of 90 seconds
  const cacheKey = `totp-used:${secret}:${token}`;
  // If this key already exists, token was already used (replay attack)
  return redis.set(cacheKey, '1', 'EX', 90, 'NX'); // NX = only set if not exists
}

React Frontend: Token Refresh with Race Condition Guard

// client/src/api/authInterceptor.js
let accessToken = null;
let refreshPromise = null;

export function setAccessToken(token) { accessToken = token; }

async function doRefresh() {
  const response = await fetch('/auth/refresh', {
    method: 'POST',
    credentials: 'include', // Sends HttpOnly refresh cookie
  });
  if (!response.ok) {
    accessToken = null;
    throw new Error('Session expired');
  }
  const data = await response.json();
  accessToken = data.accessToken;
  return accessToken;
}

async function refreshAccessToken() {
  if (!refreshPromise) {
    refreshPromise = doRefresh().finally(() => { refreshPromise = null; });
  }
  return refreshPromise; // All concurrent callers await the same promise
}

export async function authenticatedFetch(url, options = {}) {
  if (!accessToken) await refreshAccessToken();

  let response = await fetch(url, {
    ...options,
    headers: { ...options.headers, Authorization: `Bearer ${accessToken}` },
  });

  if (response.status === 401) {
    // Token may have just expired -- try one refresh
    await refreshAccessToken();
    response = await fetch(url, {
      ...options,
      headers: { ...options.headers, Authorization: `Bearer ${accessToken}` },
    });
  }

  return response;
}

MFA Strategy


Security Checklist

Known Trade-offs

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.