Secure authentication
Step 0: Research the current security landscape (do this first)
Security knowledge ages on a 6-12 month half-life. The recipes below were last verified on 2026-05-08; they may be stale by the time you read this. Before applying any pattern in this skill, fan out research scoped to the authentication primitive being implemented (passwords, sessions, JWT, OAuth, MFA, passkeys) so the recipes are interpreted against current authoritative sources, not against this file's snapshot.
Default-on, with a documented skip
Run the 4-angle research below by default. Skip ONLY when ALL of these hold:
- (a) You ran this same skill on this same primitive within the last 4 hours of the current session,
- (b) That prior research surfaced no urgent advisories for the authentication primitive being implemented (passwords, sessions, JWT, OAuth, MFA, passkeys),
- (c) You log a one-line
Research skipped because <reason> note in your response.
"I think I know" / "moving fast" / "user wants this done quickly" / "already familiar" are NOT valid skip reasons. The whole point of this preamble is that future-you should not trust this skill body's defaults until current state is checked.
Fan out 4 subagents in parallel
Each subagent returns at most 300 words of bullets with citations. Dispatch all 4 in a single message so they run concurrently.
Angle 1, Authoritative standards. Have NIST / OWASP / IETF (RFCs and Internet-Drafts) / W3C / CISA published anything new about the authentication primitive being implemented (passwords, sessions, JWT, OAuth, MFA, passkeys) in the last 6-12 months? Look for: spec finalizations, deprecations, replacement specs, RFC publications, draft revisions, NIST SP updates, OWASP project version bumps. Cite by document number plus publication date.
Angle 2, Active exploitation. What's actively being exploited that targets the authentication primitive being implemented (passwords, sessions, JWT, OAuth, MFA, passkeys)? Pull from: CISA Known Exploited Vulnerabilities (KEV) catalog (filter to last 6-12 months), recent CVE / GHSA entries with high CVSS or in-the-wild exploitation, breach postmortems and incident reports (CSRB, vendor RCAs, security-vendor research). Surface CWE patterns dominating recent KEV adds. Cite by CVE number plus advisory URL.
Angle 3, Tooling and library state. Are the libraries this skill recommends still current? What are the latest major versions in the relevant package registry (npm / PyPI / RubyGems / crates.io)? Have any been deprecated, replaced, or merged into another project? Have any flipped a secure default? Look up current versions in: registry.npmjs.org, pypi.org, rubygems.org, crates.io, pkg.go.dev. Cite by package plus version plus release date.
Angle 4, Practitioner discourse. What are practitioners and security teams talking about in the last 6 months? Pull from: OWASP Cheat Sheet Series (last-modified date matters), GitHub Security Lab posts, vendor security blogs (Cloudflare, Fastly, Snyk, Datadog, Wiz, GitGuardian), conference talks (Black Hat, DEF CON, OWASP Global AppSec, USENIX Security), SANS ISC, Krebs, recent OWASP project re-releases. Surface the patterns being adopted and the anti-patterns being called out. Cite by post URL plus author plus date.
Synthesize before applying recipes
After the 4 returns land, write a 1-paragraph "current state for the authentication primitive being implemented (passwords, sessions, JWT, OAuth, MFA, passkeys), as of <today's date>" that names:
- The current normative ceiling (what specs say SHOULD be the default in 2026).
- 1-2 active threats specific to the authentication primitive being implemented (passwords, sessions, JWT, OAuth, MFA, passkeys) from the last 6-12 months.
- Any tooling drift (deprecated lib, new default in a framework, package merged or replaced).
- Any practitioner consensus shift visible in recent cheat sheet / blog updates.
If the synthesis flags drift in this skill body's recipes (e.g., a spec finalized after 2026-05-08, a library now deprecated, a default flipped), call that out explicitly in your response and override the skill body where they conflict. The synthesis wins. The skill body is scaffolding, not scripture.
When you cannot run subagents
If subagents are not available in your runtime, the same shape applies in-line: do 4 sequential targeted searches (web search for standards, KEV catalog lookup, package registry version checks, recent cheat-sheet diff). Land the same 1-paragraph synthesis. Cost goes up; the protection does not change.
Production-ready authentication patterns. These aren't the simplest implementations, they're the ones that won't get you sued.
Authentication architecture decision
The 2020-era "session vs JWT" frame is no longer the only axis. In 2026 the question is closer to "passkey plus short-lived bound tokens" vs "session cookie." Pick by deployment shape, not by what a tutorial used.
Sessions
Use sessions when:
- Server-rendered application
- Need immediate logout / revocation
- Single domain
- Simpler to implement correctly
JWTs (with refresh tokens)
Use JWTs when:
- Multiple services need to verify auth
- Stateless verification preferred (with revocation strategy)
- Mobile app plus API
- Third-party integrations
- High-value APIs benefit from sender-constrained tokens (DPoP per RFC 9449, mTLS per RFC 8705)
Passkeys-first
Use passkeys (WebAuthn / FIDO2) as the primary factor when:
- The user agent supports WebAuthn (every current Chromium, Firefox, Safari, and major mobile browser does)
- You can run alongside passwords during transition (offer passkey enrollment after first login, keep password as fallback while user installs)
- Phishing resistance is required (NIST AAL3, government, financial, medical)
The passkey-first stance reflects 2026 consensus: WebAuthn L3 reached W3C Candidate Recommendation Snapshot 2026-01-13 (https://www.w3.org/TR/webauthn-3/) and CTAP 2.3 became a FIDO Alliance Proposed Standard 2026-02-26. See the Passkeys / WebAuthn section below.
Common mistake: Using JWTs because a tutorial did, then storing them in localStorage (XSS-vulnerable) and having no revocation strategy. Refresh-token reuse detection and full token validation (issuer, audience, scope, signing-key tenancy) are non-optional in 2026, see the Storm-0558 lesson.
Password storage
The single source of truth for password hashing across this skill. The Session and JWT examples below assume these defaults.
Default: argon2id
OWASP Password Storage Cheat Sheet (last updated 2026-05-07, https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html) lists any of 5 equivalent argon2id profiles. Pick whichever fits your server's memory budget; they're calibrated to similar work factors:
- m=47104 KiB (46 MiB), t=1, p=1
- m=19456 KiB (19 MiB), t=2, p=1
- m=12288 KiB (12 MiB), t=3, p=1
- m=9216 KiB (9 MiB), t=4, p=1
- m=7168 KiB (7 MiB), t=5, p=1
// Node, argon2 package (current 0.44.0; pre-1.0, pin by minor)
const argon2 = require('argon2');
const hash = await argon2.hash(password, {
type: argon2.argon2id,
memoryCost: 19456, // KiB, one of the 5 OWASP-equivalent profiles
timeCost: 2,
parallelism: 1
});
// Verify
const valid = await argon2.verify(hash, password);
# Python, argon2-cffi
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError
ph = PasswordHasher(
memory_cost=19456, # KiB
time_cost=2,
parallelism=1,
)
hashed = ph.hash(password)
try:
ph.verify(hashed, password)
except VerifyMismatchError:
# invalid password
pass
RFC 9106 (https://datatracker.ietf.org/doc/rfc9106/) defines a more aggressive "FIRST RECOMMENDED" profile (t=1, p=4, m=2 GiB) intended for server environments with that memory available; OWASP's 5 profiles are the practical floor.
Alternate: bcrypt
Still acceptable. OWASP says cost 10 minimum, "as large as performance allows." The current code uses cost 12, which is fine, just know the floor moved.
// Node, bcrypt (current 6.0.0)
const bcrypt = require('bcrypt');
// bcrypt has a 72-byte input limit. Pre-hash with SHA-256
// when accepting longer passphrases, OR reject inputs over 72 bytes.
const crypto = require('crypto');
function safeBcryptInput(password) {
const bytes = Buffer.byteLength(password, 'utf8');
if (bytes > 72) {
// Pre-hash to a fixed 32-byte digest, base64-encoded (44 ASCII bytes)
return crypto.createHash('sha256').update(password).digest('base64');
}
return password;
}
const hashed = await bcrypt.hash(safeBcryptInput(password), 12);
const ok = await bcrypt.compare(safeBcryptInput(password), hashed);
Alternate: scrypt
Acceptable. OWASP minimum is N=2^17, r=8, p=1.
PBKDF2: only when FIPS-140 required
PBKDF2 is the algorithm to use when FIPS-140 compliance is a hard requirement. Otherwise prefer argon2id. OWASP minimum: 600,000 iterations of PBKDF2-HMAC-SHA256, or 210,000 of PBKDF2-HMAC-SHA512.
Never
- The OS shell-execution primitive composing a password into a command line, pass via stdin or argv.
- Plain-text storage. No exceptions, no "just for now," no "we'll fix it before launch."
- Logging the plain-text password in any code path, including error handlers.
- A custom hashing scheme. Roll-your-own is the most common breach precondition.
Password policy (NIST SP 800-63B-4)
NIST SP 800-63B-4 went FINAL 2025-07-31 (https://csrc.nist.gov/pubs/sp/800/63/b/4/final). The old 800-63B was withdrawn 2025-08-01. The values below are normative. Don't deviate.
Length
- Single-factor passwords: 15-character minimum.
- Multi-factor passwords (one factor among several): 8-character minimum.
- Maximum: at least 64 characters (verifier MUST allow up to 64; it MAY allow longer).
Composition
- No composition rules. NIST 800-63B-4 §5.1.1 explicitly: "Verifiers and CSPs SHALL NOT impose other composition rules" (no "must contain uppercase / digit / symbol").
- Allow Unicode. Each Unicode code point counts as one character.
- Allow paste. Password managers depend on it.
Rotation
- No periodic rotation. Don't force "change every 90 days." Rotate only on evidence of compromise.
Blocklist (mandatory in 2026)
The verifier MUST check candidate passwords against a list of known-compromised values. Use the HaveIBeenPwned k-anonymity API (https://haveibeenpwned.com/API/v3#PwnedPasswords), you submit the first 5 chars of a SHA-1 hash, get back the suffixes that match, never send the password itself.
// Check candidate password against HIBP
const crypto = require('crypto');
async function isPwned(password) {
const sha1 = crypto.createHash('sha1').update(password).digest('hex').toUpperCase();
const prefix = sha1.slice(0, 5);
const suffix = sha1.slice(5);
const res = await fetch(`https://api.pwnedpasswords.com/range/${prefix}`, {
headers: { 'Add-Padding': 'true' }
});
if (!res.ok) {
// Fail closed on availability blip? Up to your threat model.
// Default: don't block registration if HIBP is down; log and proceed.
return false;
}
const body = await res.text();
return body.split('\n').some(line => line.startsWith(suffix));
}
Phishing resistance
NIST 800-63B-4 REQUIRES phishing resistance at AAL3. Passwords alone never reach AAL3. AAL2 with phishing resistance is what most consumer apps should target now, that means WebAuthn (passkey) or PIV/CAC, not TOTP and not SMS.
Session-based authentication
Complete Express.js implementation
const express = require('express');
const session = require('express-session');
const RedisStore = require('connect-redis').default;
const { createClient } = require('redis');
const argon2 = require('argon2');
const crypto = require('crypto');
const app = express();
// Redis client for session storage
const redisClient = createClient({ url: process.env.REDIS_URL });
redisClient.connect();
// Session configuration
app.use(session({
store: new RedisStore({ client: redisClient }),
secret: process.env.SESSION_SECRET, // At least 32 random bytes
name: 'sessionId', // Don't use default 'connect.sid'
resave: false,
saveUninitialized: false,
cookie: {
secure: process.env.NODE_ENV === 'production', // HTTPS only in prod
httpOnly: true, // Not accessible via JavaScript
sameSite: 'lax', // CSRF protection
maxAge: 24 * 60 * 60 * 1000 // 24 hours
}
}));
// Rate limiting for auth endpoints
const loginAttempts = new Map();
function checkRateLimit(ip) {
const attempts = loginAttempts.get(ip) || { count: 0, resetAt: Date.now() + 900000 };
if (Date.now() > attempts.resetAt) {
attempts.count = 0;
attempts.resetAt = Date.now() + 900000; // 15 minute window
}
if (attempts.count >= 5) {
return false;
}
attempts.count++;
loginAttempts.set(ip, attempts);
return true;
}
// Argon2id parameters, one of the 5 OWASP-equivalent profiles
const ARGON2_OPTS = {
type: argon2.argon2id,
memoryCost: 19456, // KiB
timeCost: 2,
parallelism: 1
};
// Precompute a real argon2id hash for the user-not-found timing-attack defense.
// Must be a valid hash string at the same parameters used for storage so that
// argon2.verify does the full work, a malformed string would short-circuit at
// parse time and reintroduce the timing channel.
let DUMMY_VERIFY_HASH = null;
(async () => {
DUMMY_VERIFY_HASH = await argon2.hash('argon2-timing-defense-init', ARGON2_OPTS);
})();
// Registration
app.post('/auth/register', async (req, res) => {
const { email, password } = req.body;
// Validate input
if (!email || !password) {
return res.status(400).json({ error: 'Email and password required' });
}
// NIST 800-63B-4: 15-char minimum for single-factor passwords
if (password.length < 15) {
return res.status(400).json({ error: 'Password must be at least 15 characters' });
}
// Reject up-front pwned passwords (HIBP k-anonymity)
if (await isPwned(password)) {
return res.status(400).json({ error: 'This password has appeared in a known breach. Choose a different one.' });
}
// Check if user exists
const existingUser = await db.query(
'SELECT id FROM users WHERE email = $1',
[email.toLowerCase()]
);
if (existingUser.rows.length > 0) {
// Don't reveal if email exists - use same message/timing
return res.status(400).json({ error: 'Registration failed' });
}
// Hash password
const hashedPassword = await argon2.hash(password, ARGON2_OPTS);
// Create user
const result = await db.query(
'INSERT INTO users (email, password_hash) VALUES ($1, $2) RETURNING id',
[email.toLowerCase(), hashedPassword]
);
// Create session
req.session.userId = result.rows[0].id;
req.session.createdAt = Date.now();
res.json({ success: true });
});
// Login
app.post('/auth/login', async (req, res) => {
const { email, password } = req.body;
const clientIp = req.ip;
// Rate limiting
if (!checkRateLimit(clientIp)) {
return res.status(429).json({ error: 'Too many attempts. Try again later.' });
}
// Validate input
if (!email || !password) {
return res.status(400).json({ error: 'Email and password required' });
}
// Find user
const result = await db.query(
'SELECT id, password_hash FROM users WHERE email = $1',
[email.toLowerCase()]
);
if (result.rows.length === 0) {
// Timing attack prevention: full-cost verify against a real precomputed hash.
// A malformed hash string would make argon2.verify fail at parse time,
// that's faster than the valid-user path and leaks "user not found" via
// timing. DUMMY_VERIFY_HASH is computed once at module init below so
// this path does the same work as the real verify.
if (DUMMY_VERIFY_HASH) {
await argon2.verify(DUMMY_VERIFY_HASH, password).catch(() => false);
}
return res.status(401).json({ error: 'Invalid credentials' });
}
const user = result.rows[0];
// Verify password
const isValid = await argon2.verify(user.password_hash, password).catch(() => false);
if (!isValid) {
return res.status(401).json({ error: 'Invalid credentials' });
}
// Regenerate session to prevent fixation.
// Also regenerate on privilege CHANGE (e.g. role escalation, MFA upgrade), not just login.
req.session.regenerate((err) => {
if (err) {
return res.status(500).json({ error: 'Session error' });
}
req.session.userId = user.id;
req.session.createdAt = Date.now();
// Clear rate limit on successful login
loginAttempts.delete(clientIp);
res.json({ success: true });
});
});
// Logout
app.post('/auth/logout', (req, res) => {
req.session.destroy((err) => {
if (err) {
return res.status(500).json({ error: 'Logout failed' });
}
res.clearCookie('sessionId');
res.json({ success: true });
});
});
// Auth middleware
function requireAuth(req, res, next) {
if (!req.session.userId) {
return res.status(401).json({ error: 'Authentication required' });
}
// Optional: Check session age
const maxAge = 24 * 60 * 60 * 1000; // 24 hours
if (Date.now() - req.session.createdAt > maxAge) {
req.session.destroy();
return res.status(401).json({ error: 'Session expired' });
}
next();
}
// Protected route
app.get('/api/profile', requireAuth, async (req, res) => {
const user = await db.query(
'SELECT id, email, created_at FROM users WHERE id = $1',
[req.session.userId]
);
res.json(user.rows[0]);
});
JWT authentication
Full token validation: the Storm-0558 lesson
Microsoft's Storm-0558 incident (CSRB review, https://www.cisa.gov/resources-tools/resources/CSRB-Review-Summer-2023-MEO-Intrusion) traced to OWA accepting a consumer-key-signed token for enterprise mailboxes, the token-validation library skipped the issuer / audience / scope / signing-key-tenancy checks. Validate every claim every time:
iss (issuer), MUST match your expected issuer string
aud (audience), MUST include your service identifier
exp, nbf (expiration / not-before), MUST be enforced; reject expired or future-dated tokens
scope, MUST contain the scope required for the endpoint
- Signing key, MUST belong to the issuer's tenancy, not "any key the JWKS endpoint hands out"
Complete implementation with refresh tokens
const jwt = require('jsonwebtoken');
const crypto = require('crypto');
// Token configuration
const ACCESS_TOKEN_SECRET = process.env.ACCESS_TOKEN_SECRET;
const REFRESH_TOKEN_SECRET = process.env.REFRESH_TOKEN_SECRET;
const ACCESS_TOKEN_EXPIRY = '15m';
const REFRESH_TOKEN_EXPIRY = '7d';
const ISSUER = 'https://auth.yourapp.com';
const AUDIENCE = 'https://api.yourapp.com';
// Store refresh tokens (use Redis in production).
// Each entry tracks the family chain so reuse can revoke siblings.
const refreshTokens = new Map();
function generateAccessToken(userId, scopes = []) {
return jwt.sign(
{ userId, scope: scopes.join(' '), type: 'access' },
ACCESS_TOKEN_SECRET,
{
expiresIn: ACCESS_TOKEN_EXPIRY,
issuer: ISSUER,
audience: AUDIENCE
}
);
}
function generateRefreshToken(userId, familyId = null) {
const tokenId = crypto.randomBytes(32).toString('hex');
const family = familyId || crypto.randomBytes(16).toString('hex');
const token = jwt.sign(
{ userId, tokenId, familyId: family, type: 'refresh' },
REFRESH_TOKEN_SECRET,
{
expiresIn: REFRESH_TOKEN_EXPIRY,
issuer: ISSUER,
audience: AUDIENCE
}
);
refreshTokens.set(tokenId, {
userId,
familyId: family,
createdAt: Date.now(),
used: false,
revoked: false
});
return { token, familyId: family };
}
// Revoke an entire refresh-token family (used on reuse detection).
function revokeFamily(familyId) {
for (const [id, entry] of refreshTokens) {
if (entry.familyId === familyId) {
entry.revoked = true;
}
}
}
// Login - returns both tokens
app.post('/auth/login', async (req, res) => {
const { email, password } = req.body;
// ... validation and password check ...
const accessToken = generateAccessToken(user.id, ['read', 'write']);
const { token: refreshToken } = generateRefreshToken(user.id);
// Set refresh token as httpOnly cookie
res.cookie('refreshToken', refreshToken, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
maxAge: 7 * 24 * 60 * 60 * 1000 // 7 days
});
// Return access token in response body
res.json({ accessToken });
});
// Refresh endpoint with rotation + reuse detection
app.post('/auth/refresh', (req, res) => {
const refreshToken = req.cookies.refreshToken;
if (!refreshToken) {
return res.status(401).json({ error: 'Refresh token required' });
}
let decoded;
try {
decoded = jwt.verify(refreshToken, REFRESH_TOKEN_SECRET, {
issuer: ISSUER,
audience: AUDIENCE
});
} catch (err) {
return res.status(401).json({ error: 'Invalid refresh token' });
}
const stored = refreshTokens.get(decoded.tokenId);
if (!stored || stored.revoked) {
return res.status(401).json({ error: 'Token revoked' });
}
// REUSE DETECTION: if a previously-rotated refresh token is presented,
// the family is compromised. Revoke every sibling immediately.
if (stored.used) {
revokeFamily(decoded.familyId);
return res.status(401).json({ error: 'Token reuse detected; family revoked' });
}
stored.used = true;
// Rotate: issue a new access + refresh in the same family.
const newAccess = generateAccessToken(decoded.userId, ['read', 'write']);
const { token: newRefresh } = generateRefreshToken(decoded.userId, decoded.familyId);
res.cookie('refreshToken', newRefresh, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
maxAge: 7 * 24 * 60 * 60 * 1000
});
res.json({ accessToken: newAccess });
});
// Logout - revoke entire refresh-token family
app.post('/auth/logout', (req, res) => {
const refreshToken = req.cookies.refreshToken;
if (refreshToken) {
try {
const decoded = jwt.verify(refreshToken, REFRESH_TOKEN_SECRET, {
issuer: ISSUER,
audience: AUDIENCE
});
revokeFamily(decoded.familyId);
} catch (err) {
// Token invalid, no action needed
}
}
res.clearCookie('refreshToken');
res.json({ success: true });
});
// Auth middleware for protected routes.
//
// Scope of THIS sample: single-issuer private-token deployments using HS256
// (shared secret). It enforces iss / aud / exp / scope / pinned algorithm,
// the claim-level half of the Storm-0558 lesson.
//
// What this sample does NOT cover and you MUST add for multi-issuer / OIDC
// (Azure AD / Auth0 / Cognito / etc.): the signing-key tenancy half. There:
// 1. Use a public-key algorithm (RS256, ES256, EdDSA), not HS256.
// 2. Resolve the issuer's JWKS at the issuer's well-known URL.
// 3. Pin which JWKS each trusted issuer is allowed to use, and reject any
// token whose iss does not match the JWKS that signed it. Storm-0558's
// proximate failure was OWA accepting a consumer-tenant key for an
// enterprise-tenant token because the verifier did NOT enforce this
// issuer-to-key-set binding.
// 4. Select the verifying key by the JWT's `kid`, but only from within
// the pinned key set for that issuer.
function requireAuth(requiredScope) {
return function (req, res, next) {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Access token required' });
}
const token = authHeader.substring(7);
let decoded;
try {
decoded = jwt.verify(token, ACCESS_TOKEN_SECRET, {
issuer: ISSUER,
audience: AUDIENCE,
algorithms: ['HS256'] // pin algorithm; reject 'none' and unexpected algs
});
} catch (err) {
if (err.name === 'TokenExpiredError') {
return res.status(401).json({ error: 'Token expired', code: 'TOKEN_EXPIRED' });
}
return res.status(401).json({ error: 'Invalid token' });
}
if (decoded.type !== 'access') {
return res.status(401).json({ error: 'Invalid token type' });
}
if (requiredScope) {
const scopes = (decoded.scope || '').split(' ');
if (!scopes.includes(requiredScope)) {
return res.status(403).json({ error: 'Insufficient scope' });
}
}
req.userId = decoded.userId;
req.scopes = (decoded.scope || '').split(' ');
next();
};
}
// Usage: app.get('/api/admin', requireAuth('admin'), handler)
Bound tokens for high-value APIs
Bearer tokens are stealable. For payments, healthcare, government, or any context where token theft is catastrophic, use sender-constrained tokens:
Both make stolen tokens worthless to the attacker.
Frontend token handling
// auth.js - Frontend token management
class AuthManager {
constructor() {
this.accessToken = null;
}
async login(email, password) {
const response = await fetch('/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include', // Important for cookies
body: JSON.stringify({ email, password })
});
if (!response.ok) {
throw new Error('Login failed');
}
const { accessToken } = await response.json();
this.accessToken = accessToken;
return true;
}
async refreshToken() {
const response = await fetch('/auth/refresh', {
method: 'POST',
credentials: 'include'
});
if (!response.ok) {
this.accessToken = null;
throw new Error('Session expired');
}
const { accessToken } = await response.json();
this.accessToken = accessToken;
return accessToken;
}
async fetchWithAuth(url, options = {}) {
if (!this.accessToken) {
throw new Error('Not authenticated');
}
const response = await fetch(url, {
...options,
headers: {
...options.headers,
'Authorization': `Bearer ${this.accessToken}`
}
});
// If token expired, try to refresh and retry
if (response.status === 401) {
const body = await response.json();
if (body.code === 'TOKEN_EXPIRED') {
await this.refreshToken();
// Retry original request
return fetch(url, {
...options,
headers: {
...options.headers,
'Authorization': `Bearer ${this.accessToken}`
}
});
}
}
return response;
}
async logout() {
await fetch('/auth/logout', {
method: 'POST',
credentials: 'include'
});
this.accessToken = null;
}
}
export const auth = new AuthManager();
Don't store access tokens in localStorage, they're readable by any XSS payload. In-memory (as above) plus an httpOnly refresh cookie is the standard shape. For SPAs that need to survive a page refresh, use the BroadcastChannel API to share the in-memory token across tabs and accept that a hard refresh forces a /auth/refresh call.
Passkeys / WebAuthn
WebAuthn L3 is at W3C Candidate Recommendation Snapshot as of 2026-01-13 (https://www.w3.org/TR/webauthn-3/). Comments accepted through 2026-02-10. CTAP 2.3 became a FIDO Alliance Proposed Standard 2026-02-26.
Recommended libraries:
- Node:
@simplewebauthn/server (current 13.3.0). Companion browser package: @simplewebauthn/browser.
- Python:
webauthn on PyPI (current 2.7.1). Note: the GitHub repo is duo-labs/py_webauthn, but the install command is pip install webauthn, the PyPI package name is webauthn, NOT py_webauthn.
Registration ceremony
// Node, @simplewebauthn/server
const {
generateRegistrationOptions,
verifyRegistrationResponse,
} = require('@simplewebauthn/server');
const RP_ID = 'yourapp.com'; // your effective domain
const RP_NAME = 'YourApp';
const ORIGIN = 'https://yourapp.com';
// 1. Server: build options for the browser
app.post('/auth/passkey/register/options', requireAuth(), async (req, res) => {
const user = await db.query('SELECT id, email, name FROM users WHERE id = $1', [req.userId]);
const existing = await db.query(
'SELECT credential_id, transports FROM passkeys WHERE user_id = $1',
[req.userId]
);
const options = await generateRegistrationOptions({
rpName: RP_NAME,
rpID: RP_ID,
userID: Buffer.from(String(user.rows[0].id)),
userName: user.rows[0].email,
userDisplayName: user.rows[0].name,
attestationType: 'none',
excludeCredentials: existing.rows.map(c => ({
id: c.credential_id,
transports: c.transports || undefined,
})),
authenticatorSelection: {
residentKey: 'preferred', // discoverable credentials enable conditional UI
userVerification: 'preferred',
},
});
// Store challenge for the verify step (Redis with short TTL)
await redisClient.setEx(
`webauthn:reg:${req.userId}`,
300,
options.challenge
);
res.json(options);
});
// 2. Server: verify what the browser returned
app.post('/auth/passkey/register/verify', requireAuth(), async (req, res) => {
const expectedChallenge = await redisClient.get(`webauthn:reg:${req.userId}`);
let verification;
try {
verification = await verifyRegistrationResponse({
response: req.body,
expectedChallenge,
expectedOrigin: ORIGIN,
expectedRPID: RP_ID,
requireUserVerification: false,
});
} catch (err) {
return res.status(400).json({ error: err.message });
}
if (!verification.verified || !verification.registrationInfo) {
return res.status(400).json({ error: 'Registration not verified' });
}
const { credential, credentialBackedUp, credentialDeviceType } =
verification.registrationInfo;
await db.query(
`INSERT INTO passkeys
(user_id, credential_id, public_key, counter, transports, device_type, backed_up)
VALUES ($1, $2, $3, $4, $5, $6, $7)`,
[
req.userId,
credential.id,
credential.publicKey,
credential.counter,
req.body.response?.transports || null,
credentialDeviceType,
credentialBackedUp,
]
);
await redisClient.del(`webauthn:reg:${req.userId}`);
res.json({ verified: true });
});
Install and bundle the browser helper locally. Commit the lockfile and generated
asset, and verify its checksum during deployment. If the module code remains
inline as in the examples below, generate a fresh nonce for every response and
send a CSP such as script-src 'self' 'nonce-{{CSP_NONCE}}'; replace the
placeholder in both the header and tag, and never reuse a nonce. Alternatively,
move the module code into a same-origin external file and use script-src 'self' without a nonce. A remote module graph cannot be secured by adding SRI
to only its first import.
npm install --save-exact @simplewebauthn/browser@13.3.0
npm install --save-dev --save-exact esbuild@0.28.1
npm ci
mkdir -p public/vendor
npx esbuild @simplewebauthn/browser --bundle --format=esm --platform=browser \
--outfile=public/vendor/simplewebauthn-browser-13.3.0.mjs
sha256sum public/vendor/simplewebauthn-browser-13.3.0.mjs \
> public/vendor/SHA256SUMS
sha256sum -c public/vendor/SHA256SUMS
<!-- Browser, local @simplewebauthn/browser bundle -->
<script type="module" nonce="{{CSP_NONCE}}">
import { startRegistration }
from '/vendor/simplewebauthn-browser-13.3.0.mjs';
async function enrollPasskey() {
const optsRes = await fetch('/auth/passkey/register/options', { method: 'POST', credentials: 'include' });
const options = await optsRes.json();
const attResp = await startRegistration({ optionsJSON: options });
const verRes = await fetch('/auth/passkey/register/verify', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(attResp),
});
return verRes.json();
}
document.getElementById('enroll').addEventListener('click', enrollPasskey);
</script>
Authentication ceremony (with conditional UI)
Conditional UI lets the browser surface passkeys directly inside the username autofill dropdown, the user picks a passkey from the same UI they'd use to autofill an email.
// Node, server side
const {
generateAuthenticationOptions,
verifyAuthenticationResponse,
} = require('@simplewebauthn/server');
app.post('/auth/passkey/login/options', async (req, res) => {
const options = await generateAuthenticationOptions({
rpID: RP_ID,
userVerification: 'preferred',
// allowCredentials omitted → discoverable credentials → conditional UI works
});
// Tie the challenge to a temporary session marker
const challengeId = crypto.randomBytes(16).toString('hex');
await redisClient.setEx(`webauthn:auth:${challengeId}`, 300, options.challenge);
res.json({ options, challengeId });
});
app.post('/auth/passkey/login/verify', async (req, res) => {
const { challengeId, response } = req.body;
const expectedChallenge = await redisClient.get(`webauthn:auth:${challengeId}`);
if (!expectedChallenge) {
return res.status(400).json({ error: 'Challenge expired' });
}
const credentialId = response.id;
const stored = await db.query(
`SELECT user_id, public_key, counter, transports FROM passkeys WHERE credential_id = $1`,
[credentialId]
);
if (stored.rows.length === 0) {
return res.status(401).json({ error: 'Unknown credential' });
}
let verification;
try {
verification = await verifyAuthenticationResponse({
response,
expectedChallenge,
expectedOrigin: ORIGIN,
expectedRPID: RP_ID,
credential: {
id: credentialId,
publicKey: stored.rows[0].public_key,
counter: stored.rows[0].counter,
transports: stored.rows[0].transports || undefined,
},
requireUserVerification: false,
});
} catch (err) {
return res.status(401).json({ error: err.message });
}
if (!verification.verified) {
return res.status(401).json({ error: 'Authentication not verified' });
}
// Persist new counter
await db.query(
`UPDATE passkeys SET counter = $1, last_used_at = NOW() WHERE credential_id = $2`,
[verification.authenticationInfo.newCounter, credentialId]
);
// Issue session/tokens as usual
req.session.regenerate(() => {
req.session.userId = stored.rows[0].user_id;
res.json({ verified: true });
});
});
<!-- Browser, discoverable credential + conditional UI -->
<input type="email" name="email" autocomplete="username webauthn">
<script type="module" nonce="{{CSP_NONCE}}">
import { startAuthentication, browserSupportsWebAuthnAutofill }
from '/vendor/simplewebauthn-browser-13.3.0.mjs';
if (await browserSupportsWebAuthnAutofill()) {
const optsRes = await fetch('/auth/passkey/login/options', { method: 'POST' });
const { options, challengeId } = await optsRes.json();
const authResp = await startAuthentication({
optionsJSON: options,
useBrowserAutofill: true, // conditional UI
});
await fetch('/auth/passkey/login/verify', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ challengeId, response: authResp }),
});
location.href = '/dashboard';
}
</script>
WebAuthn L3 signal methods
L3 adds PublicKeyCredential static methods so the relying party can keep syncable passkeys aligned with server state without forcing a re-enrollment:
signalUnknownCredential({ rpId, credentialId }), call after a verify attempt against a credential the server no longer knows about. The authenticator hides it from the user's account-picker UI.
signalAllAcceptedCredentials({ rpId, userId, allAcceptedCredentialIds }), call after the server's credential list changes (revoke, enroll). The authenticator prunes anything not on the list.
signalCurrentUserDetails({ rpId, userId, name, displayName }), call after profile changes. The authenticator updates labels in the picker UI.
These are advisory and best-effort; treat them as housekeeping, not security boundaries.
When to use webauthn (Python)
# pip install webauthn # PyPI package name is `webauthn`, NOT py_webauthn
from webauthn import (
generate_registration_options,
verify_registration_response,
generate_authentication_options,
verify_authentication_response,
)
from webauthn.helpers.structs import (
AuthenticatorSelectionCriteria,
ResidentKeyRequirement,
UserVerificationRequirement,
)
RP_ID = "yourapp.com"
RP_NAME = "YourApp"
ORIGIN = "https://yourapp.com"
options = generate_registration_options(
rp_id=RP_ID,
rp_name=RP_NAME,
user_id=str(user_id).encode(),
user_name=user_email,
authenticator_selection=AuthenticatorSelectionCriteria(
resident_key=ResidentKeyRequirement.PREFERRED,
user_verification=UserVerificationRequirement.PREFERRED,
),
)
Password reset flow
Secure implementation
const crypto = require('crypto');
// Request password reset
app.post('/auth/forgot-password', async (req, res) => {
const { email } = req.body;
// Always return success to prevent email enumeration
res.json({ message: 'If an account exists, a reset link has been sent.' });
// Find user (async, after response)
const result = await db.query(
'SELECT id FROM users WHERE email = $1',
[email.toLowerCase()]
);
if (result.rows.length === 0) {
return; // User doesn't exist, but don't reveal that
}
const user = result.rows[0];
// Generate secure token
const token = crypto.randomBytes(32).toString('hex');
const tokenHash = crypto.createHash('sha256').update(token).digest('hex');
const expiresAt = new Date(Date.now() + 3600000); // 1 hour
// Store hashed token (not plain token)
await db.query(
'INSERT INTO password_resets (user_id, token_hash, expires_at) VALUES ($1, $2, $3)',
[user.id, tokenHash, expiresAt]
);
// Send email with plain token
const resetUrl = `https://yourapp.com/reset-password?token=${token}`;
await sendEmail(email, 'Password Reset', `Reset your password: ${resetUrl}`);
});
// Reset password
app.post('/auth/reset-password', async (req, res) => {
const { token, newPassword } = req.body;
if (!token || !newPassword) {
return res.status(400).json({ error: 'Token and new password required' });
}
// NIST 800-63B-4: 15-char minimum
if (newPassword.length < 15) {
return res.status(400).json({ error: 'Password must be at least 15 characters' });
}
if (await isPwned(newPassword)) {
return res.status(400).json({ error: 'This password has appeared in a known breach. Choose a different one.' });
}
// Hash the provided token to compare with stored hash
const tokenHash = crypto.createHash('sha256').update(token).digest('hex');
// Find valid reset token
const result = await db.query(
`SELECT user_id FROM password_resets
WHERE token_hash = $1 AND expires_at > NOW() AND used = false`,
[tokenHash]
);
if (result.rows.length === 0) {
return res.status(400).json({ error: 'Invalid or expired token' });
}
const userId = result.rows[0].user_id;
…(truncated)
1---
2name: secure-auth
3description: Secure authentication patterns (OWASP, NIST). Use for login, registration, password reset, sessions, JWT, OAuth, MFA, passkeys.
4metadata:
5 source: https://skillmd.com/skills/jamditis/secure-auth
6---
7
8# Secure authentication
9
10## Step 0: Research the current security landscape (do this first)
11
12> Security knowledge ages on a 6-12 month half-life. The recipes below were last verified on 2026-05-08; they may be stale by the time you read this. Before applying any pattern in this skill, fan out research scoped to the authentication primitive being implemented (passwords, sessions, JWT, OAuth, MFA, passkeys) so the recipes are interpreted against current authoritative sources, not against this file's snapshot.
13
14### Default-on, with a documented skip
15
16Run the 4-angle research below by default. Skip ONLY when ALL of these hold:
17
18- (a) You ran this same skill on this same primitive within the last 4 hours of the current session,
19- (b) That prior research surfaced no urgent advisories for the authentication primitive being implemented (passwords, sessions, JWT, OAuth, MFA, passkeys),
20- (c) You log a one-line `Research skipped because <reason>` note in your response.
21
22"I think I know" / "moving fast" / "user wants this done quickly" / "already familiar" are NOT valid skip reasons. The whole point of this preamble is that future-you should not trust this skill body's defaults until current state is checked.
23
24### Fan out 4 subagents in parallel
25
26Each subagent returns at most 300 words of bullets with citations. Dispatch all 4 in a single message so they run concurrently.
27
28**Angle 1, Authoritative standards.** Have NIST / OWASP / IETF (RFCs and Internet-Drafts) / W3C / CISA published anything new about the authentication primitive being implemented (passwords, sessions, JWT, OAuth, MFA, passkeys) in the last 6-12 months? Look for: spec finalizations, deprecations, replacement specs, RFC publications, draft revisions, NIST SP updates, OWASP project version bumps. Cite by document number plus publication date.
29
30**Angle 2, Active exploitation.** What's actively being exploited that targets the authentication primitive being implemented (passwords, sessions, JWT, OAuth, MFA, passkeys)? Pull from: CISA Known Exploited Vulnerabilities (KEV) catalog (filter to last 6-12 months), recent CVE / GHSA entries with high CVSS or in-the-wild exploitation, breach postmortems and incident reports (CSRB, vendor RCAs, security-vendor research). Surface CWE patterns dominating recent KEV adds. Cite by CVE number plus advisory URL.
31
32**Angle 3, Tooling and library state.** Are the libraries this skill recommends still current? What are the latest major versions in the relevant package registry (npm / PyPI / RubyGems / crates.io)? Have any been deprecated, replaced, or merged into another project? Have any flipped a secure default? Look up current versions in: registry.npmjs.org, pypi.org, rubygems.org, crates.io, pkg.go.dev. Cite by package plus version plus release date.
33
34**Angle 4, Practitioner discourse.** What are practitioners and security teams talking about in the last 6 months? Pull from: OWASP Cheat Sheet Series (last-modified date matters), GitHub Security Lab posts, vendor security blogs (Cloudflare, Fastly, Snyk, Datadog, Wiz, GitGuardian), conference talks (Black Hat, DEF CON, OWASP Global AppSec, USENIX Security), SANS ISC, Krebs, recent OWASP project re-releases. Surface the patterns being adopted and the anti-patterns being called out. Cite by post URL plus author plus date.
35
36### Synthesize before applying recipes
37
38After the 4 returns land, write a 1-paragraph "current state for the authentication primitive being implemented (passwords, sessions, JWT, OAuth, MFA, passkeys), as of <today's date>" that names:
39
40- The current normative ceiling (what specs say SHOULD be the default in 2026).
41- 1-2 active threats specific to the authentication primitive being implemented (passwords, sessions, JWT, OAuth, MFA, passkeys) from the last 6-12 months.
42- Any tooling drift (deprecated lib, new default in a framework, package merged or replaced).
43- Any practitioner consensus shift visible in recent cheat sheet / blog updates.
44
45If the synthesis flags drift in this skill body's recipes (e.g., a spec finalized after 2026-05-08, a library now deprecated, a default flipped), call that out explicitly in your response and override the skill body where they conflict. The synthesis wins. The skill body is scaffolding, not scripture.
46
47### When you cannot run subagents
48
49If subagents are not available in your runtime, the same shape applies in-line: do 4 sequential targeted searches (web search for standards, KEV catalog lookup, package registry version checks, recent cheat-sheet diff). Land the same 1-paragraph synthesis. Cost goes up; the protection does not change.
50
51---
52
53Production-ready authentication patterns. These aren't the simplest implementations, they're the ones that won't get you sued.
54
55## Authentication architecture decision
56
57The 2020-era "session vs JWT" frame is no longer the only axis. In 2026 the question is closer to "passkey plus short-lived bound tokens" vs "session cookie." Pick by deployment shape, not by what a tutorial used.
58
59### Sessions
60
61Use sessions when:
62- Server-rendered application
63- Need immediate logout / revocation
64- Single domain
65- Simpler to implement correctly
66
67### JWTs (with refresh tokens)
68
69Use JWTs when:
70- Multiple services need to verify auth
71- Stateless verification preferred (with revocation strategy)
72- Mobile app plus API
73- Third-party integrations
74- High-value APIs benefit from sender-constrained tokens (DPoP per RFC 9449, mTLS per RFC 8705)
75
76### Passkeys-first
77
78Use passkeys (WebAuthn / FIDO2) as the primary factor when:
79- The user agent supports WebAuthn (every current Chromium, Firefox, Safari, and major mobile browser does)
80- You can run alongside passwords during transition (offer passkey enrollment after first login, keep password as fallback while user installs)
81- Phishing resistance is required (NIST AAL3, government, financial, medical)
82
83The passkey-first stance reflects 2026 consensus: WebAuthn L3 reached W3C Candidate Recommendation Snapshot 2026-01-13 (https://www.w3.org/TR/webauthn-3/) and CTAP 2.3 became a FIDO Alliance Proposed Standard 2026-02-26. See the Passkeys / WebAuthn section below.
84
85**Common mistake:** Using JWTs because a tutorial did, then storing them in localStorage (XSS-vulnerable) and having no revocation strategy. Refresh-token reuse detection and full token validation (issuer, audience, scope, signing-key tenancy) are non-optional in 2026, see the Storm-0558 lesson.
86
87## Password storage
88
89The single source of truth for password hashing across this skill. The Session and JWT examples below assume these defaults.
90
91### Default: argon2id
92
93OWASP Password Storage Cheat Sheet (last updated 2026-05-07, https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html) lists any of 5 equivalent argon2id profiles. Pick whichever fits your server's memory budget; they're calibrated to similar work factors:
94
95- m=47104 KiB (46 MiB), t=1, p=1
96- m=19456 KiB (19 MiB), t=2, p=1
97- m=12288 KiB (12 MiB), t=3, p=1
98- m=9216 KiB (9 MiB), t=4, p=1
99- m=7168 KiB (7 MiB), t=5, p=1
100
101```javascript
102// Node, argon2 package (current 0.44.0; pre-1.0, pin by minor)
103const argon2 = require('argon2');
104
105const hash = await argon2.hash(password, {
106 type: argon2.argon2id,
107 memoryCost: 19456, // KiB, one of the 5 OWASP-equivalent profiles
108 timeCost: 2,
109 parallelism: 1
110});
111
112// Verify
113const valid = await argon2.verify(hash, password);
114```
115
116```python
117# Python, argon2-cffi
118from argon2 import PasswordHasher
119from argon2.exceptions import VerifyMismatchError
120
121ph = PasswordHasher(
122 memory_cost=19456, # KiB
123 time_cost=2,
124 parallelism=1,
125)
126
127hashed = ph.hash(password)
128
129try:
130 ph.verify(hashed, password)
131except VerifyMismatchError:
132 # invalid password
133 pass
134```
135
136RFC 9106 (https://datatracker.ietf.org/doc/rfc9106/) defines a more aggressive "FIRST RECOMMENDED" profile (t=1, p=4, m=2 GiB) intended for server environments with that memory available; OWASP's 5 profiles are the practical floor.
137
138### Alternate: bcrypt
139
140Still acceptable. OWASP says cost 10 minimum, "as large as performance allows." The current code uses cost 12, which is fine, just know the floor moved.
141
142```javascript
143// Node, bcrypt (current 6.0.0)
144const bcrypt = require('bcrypt');
145
146// bcrypt has a 72-byte input limit. Pre-hash with SHA-256
147// when accepting longer passphrases, OR reject inputs over 72 bytes.
148const crypto = require('crypto');
149
150function safeBcryptInput(password) {
151 const bytes = Buffer.byteLength(password, 'utf8');
152 if (bytes > 72) {
153 // Pre-hash to a fixed 32-byte digest, base64-encoded (44 ASCII bytes)
154 return crypto.createHash('sha256').update(password).digest('base64');
155 }
156 return password;
157}
158
159const hashed = await bcrypt.hash(safeBcryptInput(password), 12);
160const ok = await bcrypt.compare(safeBcryptInput(password), hashed);
161```
162
163### Alternate: scrypt
164
165Acceptable. OWASP minimum is N=2^17, r=8, p=1.
166
167### PBKDF2: only when FIPS-140 required
168
169PBKDF2 is the algorithm to use when FIPS-140 compliance is a hard requirement. Otherwise prefer argon2id. OWASP minimum: 600,000 iterations of PBKDF2-HMAC-SHA256, or 210,000 of PBKDF2-HMAC-SHA512.
170
171### Never
172
173- The OS shell-execution primitive composing a password into a command line, pass via stdin or argv.
174- Plain-text storage. No exceptions, no "just for now," no "we'll fix it before launch."
175- Logging the plain-text password in any code path, including error handlers.
176- A custom hashing scheme. Roll-your-own is the most common breach precondition.
177
178## Password policy (NIST SP 800-63B-4)
179
180NIST SP 800-63B-4 went FINAL 2025-07-31 (https://csrc.nist.gov/pubs/sp/800/63/b/4/final). The old 800-63B was withdrawn 2025-08-01. The values below are normative. Don't deviate.
181
182### Length
183
184- Single-factor passwords: **15-character minimum**.
185- Multi-factor passwords (one factor among several): 8-character minimum.
186- Maximum: at least **64 characters** (verifier MUST allow up to 64; it MAY allow longer).
187
188### Composition
189
190- **No composition rules.** NIST 800-63B-4 §5.1.1 explicitly: "Verifiers and CSPs SHALL NOT impose other composition rules" (no "must contain uppercase / digit / symbol").
191- **Allow Unicode.** Each Unicode code point counts as one character.
192- **Allow paste.** Password managers depend on it.
193
194### Rotation
195
196- **No periodic rotation.** Don't force "change every 90 days." Rotate only on evidence of compromise.
197
198### Blocklist (mandatory in 2026)
199
200The verifier MUST check candidate passwords against a list of known-compromised values. Use the HaveIBeenPwned k-anonymity API (https://haveibeenpwned.com/API/v3#PwnedPasswords), you submit the first 5 chars of a SHA-1 hash, get back the suffixes that match, never send the password itself.
201
202```javascript
203// Check candidate password against HIBP
204const crypto = require('crypto');
205
206async function isPwned(password) {
207 const sha1 = crypto.createHash('sha1').update(password).digest('hex').toUpperCase();
208 const prefix = sha1.slice(0, 5);
209 const suffix = sha1.slice(5);
210
211 const res = await fetch(`https://api.pwnedpasswords.com/range/${prefix}`, {
212 headers: { 'Add-Padding': 'true' }
213 });
214 if (!res.ok) {
215 // Fail closed on availability blip? Up to your threat model.
216 // Default: don't block registration if HIBP is down; log and proceed.
217 return false;
218 }
219 const body = await res.text();
220 return body.split('\n').some(line => line.startsWith(suffix));
221}
222```
223
224### Phishing resistance
225
226NIST 800-63B-4 REQUIRES phishing resistance at AAL3. Passwords alone never reach AAL3. AAL2 with phishing resistance is what most consumer apps should target now, that means WebAuthn (passkey) or PIV/CAC, not TOTP and not SMS.
227
228## Session-based authentication
229
230### Complete Express.js implementation
231
232```javascript
233const express = require('express');
234const session = require('express-session');
235const RedisStore = require('connect-redis').default;
236const { createClient } = require('redis');
237const argon2 = require('argon2');
238const crypto = require('crypto');
239
240const app = express();
241
242// Redis client for session storage
243const redisClient = createClient({ url: process.env.REDIS_URL });
244redisClient.connect();
245
246// Session configuration
247app.use(session({
248 store: new RedisStore({ client: redisClient }),
249 secret: process.env.SESSION_SECRET, // At least 32 random bytes
250 name: 'sessionId', // Don't use default 'connect.sid'
251 resave: false,
252 saveUninitialized: false,
253 cookie: {
254 secure: process.env.NODE_ENV === 'production', // HTTPS only in prod
255 httpOnly: true, // Not accessible via JavaScript
256 sameSite: 'lax', // CSRF protection
257 maxAge: 24 * 60 * 60 * 1000 // 24 hours
258 }
259}));
260
261// Rate limiting for auth endpoints
262const loginAttempts = new Map();
263
264function checkRateLimit(ip) {
265 const attempts = loginAttempts.get(ip) || { count: 0, resetAt: Date.now() + 900000 };
266
267 if (Date.now() > attempts.resetAt) {
268 attempts.count = 0;
269 attempts.resetAt = Date.now() + 900000; // 15 minute window
270 }
271
272 if (attempts.count >= 5) {
273 return false;
274 }
275
276 attempts.count++;
277 loginAttempts.set(ip, attempts);
278 return true;
279}
280
281// Argon2id parameters, one of the 5 OWASP-equivalent profiles
282const ARGON2_OPTS = {
283 type: argon2.argon2id,
284 memoryCost: 19456, // KiB
285 timeCost: 2,
286 parallelism: 1
287};
288
289// Precompute a real argon2id hash for the user-not-found timing-attack defense.
290// Must be a valid hash string at the same parameters used for storage so that
291// argon2.verify does the full work, a malformed string would short-circuit at
292// parse time and reintroduce the timing channel.
293let DUMMY_VERIFY_HASH = null;
294(async () => {
295 DUMMY_VERIFY_HASH = await argon2.hash('argon2-timing-defense-init', ARGON2_OPTS);
296})();
297
298// Registration
299app.post('/auth/register', async (req, res) => {
300 const { email, password } = req.body;
301
302 // Validate input
303 if (!email || !password) {
304 return res.status(400).json({ error: 'Email and password required' });
305 }
306
307 // NIST 800-63B-4: 15-char minimum for single-factor passwords
308 if (password.length < 15) {
309 return res.status(400).json({ error: 'Password must be at least 15 characters' });
310 }
311
312 // Reject up-front pwned passwords (HIBP k-anonymity)
313 if (await isPwned(password)) {
314 return res.status(400).json({ error: 'This password has appeared in a known breach. Choose a different one.' });
315 }
316
317 // Check if user exists
318 const existingUser = await db.query(
319 'SELECT id FROM users WHERE email = $1',
320 [email.toLowerCase()]
321 );
322
323 if (existingUser.rows.length > 0) {
324 // Don't reveal if email exists - use same message/timing
325 return res.status(400).json({ error: 'Registration failed' });
326 }
327
328 // Hash password
329 const hashedPassword = await argon2.hash(password, ARGON2_OPTS);
330
331 // Create user
332 const result = await db.query(
333 'INSERT INTO users (email, password_hash) VALUES ($1, $2) RETURNING id',
334 [email.toLowerCase(), hashedPassword]
335 );
336
337 // Create session
338 req.session.userId = result.rows[0].id;
339 req.session.createdAt = Date.now();
340
341 res.json({ success: true });
342});
343
344// Login
345app.post('/auth/login', async (req, res) => {
346 const { email, password } = req.body;
347 const clientIp = req.ip;
348
349 // Rate limiting
350 if (!checkRateLimit(clientIp)) {
351 return res.status(429).json({ error: 'Too many attempts. Try again later.' });
352 }
353
354 // Validate input
355 if (!email || !password) {
356 return res.status(400).json({ error: 'Email and password required' });
357 }
358
359 // Find user
360 const result = await db.query(
361 'SELECT id, password_hash FROM users WHERE email = $1',
362 [email.toLowerCase()]
363 );
364
365 if (result.rows.length === 0) {
366 // Timing attack prevention: full-cost verify against a real precomputed hash.
367 // A malformed hash string would make argon2.verify fail at parse time,
368 // that's faster than the valid-user path and leaks "user not found" via
369 // timing. DUMMY_VERIFY_HASH is computed once at module init below so
370 // this path does the same work as the real verify.
371 if (DUMMY_VERIFY_HASH) {
372 await argon2.verify(DUMMY_VERIFY_HASH, password).catch(() => false);
373 }
374 return res.status(401).json({ error: 'Invalid credentials' });
375 }
376
377 const user = result.rows[0];
378
379 // Verify password
380 const isValid = await argon2.verify(user.password_hash, password).catch(() => false);
381
382 if (!isValid) {
383 return res.status(401).json({ error: 'Invalid credentials' });
384 }
385
386 // Regenerate session to prevent fixation.
387 // Also regenerate on privilege CHANGE (e.g. role escalation, MFA upgrade), not just login.
388 req.session.regenerate((err) => {
389 if (err) {
390 return res.status(500).json({ error: 'Session error' });
391 }
392
393 req.session.userId = user.id;
394 req.session.createdAt = Date.now();
395
396 // Clear rate limit on successful login
397 loginAttempts.delete(clientIp);
398
399 res.json({ success: true });
400 });
401});
402
403// Logout
404app.post('/auth/logout', (req, res) => {
405 req.session.destroy((err) => {
406 if (err) {
407 return res.status(500).json({ error: 'Logout failed' });
408 }
409 res.clearCookie('sessionId');
410 res.json({ success: true });
411 });
412});
413
414// Auth middleware
415function requireAuth(req, res, next) {
416 if (!req.session.userId) {
417 return res.status(401).json({ error: 'Authentication required' });
418 }
419
420 // Optional: Check session age
421 const maxAge = 24 * 60 * 60 * 1000; // 24 hours
422 if (Date.now() - req.session.createdAt > maxAge) {
423 req.session.destroy();
424 return res.status(401).json({ error: 'Session expired' });
425 }
426
427 next();
428}
429
430// Protected route
431app.get('/api/profile', requireAuth, async (req, res) => {
432 const user = await db.query(
433 'SELECT id, email, created_at FROM users WHERE id = $1',
434 [req.session.userId]
435 );
436 res.json(user.rows[0]);
437});
438```
439
440## JWT authentication
441
442### Full token validation: the Storm-0558 lesson
443
444Microsoft's Storm-0558 incident (CSRB review, https://www.cisa.gov/resources-tools/resources/CSRB-Review-Summer-2023-MEO-Intrusion) traced to OWA accepting a consumer-key-signed token for enterprise mailboxes, the token-validation library skipped the issuer / audience / scope / signing-key-tenancy checks. Validate every claim every time:
445
446- `iss` (issuer), MUST match your expected issuer string
447- `aud` (audience), MUST include your service identifier
448- `exp`, `nbf` (expiration / not-before), MUST be enforced; reject expired or future-dated tokens
449- `scope`, MUST contain the scope required for the endpoint
450- Signing key, MUST belong to the issuer's tenancy, not "any key the JWKS endpoint hands out"
451
452### Complete implementation with refresh tokens
453
454```javascript
455const jwt = require('jsonwebtoken');
456const crypto = require('crypto');
457
458// Token configuration
459const ACCESS_TOKEN_SECRET = process.env.ACCESS_TOKEN_SECRET;
460const REFRESH_TOKEN_SECRET = process.env.REFRESH_TOKEN_SECRET;
461const ACCESS_TOKEN_EXPIRY = '15m';
462const REFRESH_TOKEN_EXPIRY = '7d';
463const ISSUER = 'https://auth.yourapp.com';
464const AUDIENCE = 'https://api.yourapp.com';
465
466// Store refresh tokens (use Redis in production).
467// Each entry tracks the family chain so reuse can revoke siblings.
468const refreshTokens = new Map();
469
470function generateAccessToken(userId, scopes = []) {
471 return jwt.sign(
472 { userId, scope: scopes.join(' '), type: 'access' },
473 ACCESS_TOKEN_SECRET,
474 {
475 expiresIn: ACCESS_TOKEN_EXPIRY,
476 issuer: ISSUER,
477 audience: AUDIENCE
478 }
479 );
480}
481
482function generateRefreshToken(userId, familyId = null) {
483 const tokenId = crypto.randomBytes(32).toString('hex');
484 const family = familyId || crypto.randomBytes(16).toString('hex');
485 const token = jwt.sign(
486 { userId, tokenId, familyId: family, type: 'refresh' },
487 REFRESH_TOKEN_SECRET,
488 {
489 expiresIn: REFRESH_TOKEN_EXPIRY,
490 issuer: ISSUER,
491 audience: AUDIENCE
492 }
493 );
494
495 refreshTokens.set(tokenId, {
496 userId,
497 familyId: family,
498 createdAt: Date.now(),
499 used: false,
500 revoked: false
501 });
502
503 return { token, familyId: family };
504}
505
506// Revoke an entire refresh-token family (used on reuse detection).
507function revokeFamily(familyId) {
508 for (const [id, entry] of refreshTokens) {
509 if (entry.familyId === familyId) {
510 entry.revoked = true;
511 }
512 }
513}
514
515// Login - returns both tokens
516app.post('/auth/login', async (req, res) => {
517 const { email, password } = req.body;
518
519 // ... validation and password check ...
520
521 const accessToken = generateAccessToken(user.id, ['read', 'write']);
522 const { token: refreshToken } = generateRefreshToken(user.id);
523
524 // Set refresh token as httpOnly cookie
525 res.cookie('refreshToken', refreshToken, {
526 httpOnly: true,
527 secure: process.env.NODE_ENV === 'production',
528 sameSite: 'strict',
529 maxAge: 7 * 24 * 60 * 60 * 1000 // 7 days
530 });
531
532 // Return access token in response body
533 res.json({ accessToken });
534});
535
536// Refresh endpoint with rotation + reuse detection
537app.post('/auth/refresh', (req, res) => {
538 const refreshToken = req.cookies.refreshToken;
539
540 if (!refreshToken) {
541 return res.status(401).json({ error: 'Refresh token required' });
542 }
543
544 let decoded;
545 try {
546 decoded = jwt.verify(refreshToken, REFRESH_TOKEN_SECRET, {
547 issuer: ISSUER,
548 audience: AUDIENCE
549 });
550 } catch (err) {
551 return res.status(401).json({ error: 'Invalid refresh token' });
552 }
553
554 const stored = refreshTokens.get(decoded.tokenId);
555 if (!stored || stored.revoked) {
556 return res.status(401).json({ error: 'Token revoked' });
557 }
558
559 // REUSE DETECTION: if a previously-rotated refresh token is presented,
560 // the family is compromised. Revoke every sibling immediately.
561 if (stored.used) {
562 revokeFamily(decoded.familyId);
563 return res.status(401).json({ error: 'Token reuse detected; family revoked' });
564 }
565
566 stored.used = true;
567
568 // Rotate: issue a new access + refresh in the same family.
569 const newAccess = generateAccessToken(decoded.userId, ['read', 'write']);
570 const { token: newRefresh } = generateRefreshToken(decoded.userId, decoded.familyId);
571
572 res.cookie('refreshToken', newRefresh, {
573 httpOnly: true,
574 secure: process.env.NODE_ENV === 'production',
575 sameSite: 'strict',
576 maxAge: 7 * 24 * 60 * 60 * 1000
577 });
578
579 res.json({ accessToken: newAccess });
580});
581
582// Logout - revoke entire refresh-token family
583app.post('/auth/logout', (req, res) => {
584 const refreshToken = req.cookies.refreshToken;
585
586 if (refreshToken) {
587 try {
588 const decoded = jwt.verify(refreshToken, REFRESH_TOKEN_SECRET, {
589 issuer: ISSUER,
590 audience: AUDIENCE
591 });
592 revokeFamily(decoded.familyId);
593 } catch (err) {
594 // Token invalid, no action needed
595 }
596 }
597
598 res.clearCookie('refreshToken');
599 res.json({ success: true });
600});
601
602// Auth middleware for protected routes.
603//
604// Scope of THIS sample: single-issuer private-token deployments using HS256
605// (shared secret). It enforces iss / aud / exp / scope / pinned algorithm,
606// the claim-level half of the Storm-0558 lesson.
607//
608// What this sample does NOT cover and you MUST add for multi-issuer / OIDC
609// (Azure AD / Auth0 / Cognito / etc.): the signing-key tenancy half. There:
610// 1. Use a public-key algorithm (RS256, ES256, EdDSA), not HS256.
611// 2. Resolve the issuer's JWKS at the issuer's well-known URL.
612// 3. Pin which JWKS each trusted issuer is allowed to use, and reject any
613// token whose iss does not match the JWKS that signed it. Storm-0558's
614// proximate failure was OWA accepting a consumer-tenant key for an
615// enterprise-tenant token because the verifier did NOT enforce this
616// issuer-to-key-set binding.
617// 4. Select the verifying key by the JWT's `kid`, but only from within
618// the pinned key set for that issuer.
619function requireAuth(requiredScope) {
620 return function (req, res, next) {
621 const authHeader = req.headers.authorization;
622
623 if (!authHeader || !authHeader.startsWith('Bearer ')) {
624 return res.status(401).json({ error: 'Access token required' });
625 }
626
627 const token = authHeader.substring(7);
628
629 let decoded;
630 try {
631 decoded = jwt.verify(token, ACCESS_TOKEN_SECRET, {
632 issuer: ISSUER,
633 audience: AUDIENCE,
634 algorithms: ['HS256'] // pin algorithm; reject 'none' and unexpected algs
635 });
636 } catch (err) {
637 if (err.name === 'TokenExpiredError') {
638 return res.status(401).json({ error: 'Token expired', code: 'TOKEN_EXPIRED' });
639 }
640 return res.status(401).json({ error: 'Invalid token' });
641 }
642
643 if (decoded.type !== 'access') {
644 return res.status(401).json({ error: 'Invalid token type' });
645 }
646
647 if (requiredScope) {
648 const scopes = (decoded.scope || '').split(' ');
649 if (!scopes.includes(requiredScope)) {
650 return res.status(403).json({ error: 'Insufficient scope' });
651 }
652 }
653
654 req.userId = decoded.userId;
655 req.scopes = (decoded.scope || '').split(' ');
656 next();
657 };
658}
659
660// Usage: app.get('/api/admin', requireAuth('admin'), handler)
661```
662
663### Bound tokens for high-value APIs
664
665Bearer tokens are stealable. For payments, healthcare, government, or any context where token theft is catastrophic, use sender-constrained tokens:
666
667- **DPoP (RFC 9449, https://datatracker.ietf.org/doc/rfc9449/)**, client signs each request with a private key; the access token is bound to the public-key thumbprint (`cnf.jkt` claim). Token alone is useless without the key.
668- **mTLS (RFC 8705, https://datatracker.ietf.org/doc/rfc8705/)**, token bound to the client certificate used in the TLS handshake (`cnf.x5t#S256` claim).
669
670Both make stolen tokens worthless to the attacker.
671
672### Frontend token handling
673
674```javascript
675// auth.js - Frontend token management
676
677class AuthManager {
678 constructor() {
679 this.accessToken = null;
680 }
681
682 async login(email, password) {
683 const response = await fetch('/auth/login', {
684 method: 'POST',
685 headers: { 'Content-Type': 'application/json' },
686 credentials: 'include', // Important for cookies
687 body: JSON.stringify({ email, password })
688 });
689
690 if (!response.ok) {
691 throw new Error('Login failed');
692 }
693
694 const { accessToken } = await response.json();
695 this.accessToken = accessToken;
696
697 return true;
698 }
699
700 async refreshToken() {
701 const response = await fetch('/auth/refresh', {
702 method: 'POST',
703 credentials: 'include'
704 });
705
706 if (!response.ok) {
707 this.accessToken = null;
708 throw new Error('Session expired');
709 }
710
711 const { accessToken } = await response.json();
712 this.accessToken = accessToken;
713
714 return accessToken;
715 }
716
717 async fetchWithAuth(url, options = {}) {
718 if (!this.accessToken) {
719 throw new Error('Not authenticated');
720 }
721
722 const response = await fetch(url, {
723 ...options,
724 headers: {
725 ...options.headers,
726 'Authorization': `Bearer ${this.accessToken}`
727 }
728 });
729
730 // If token expired, try to refresh and retry
731 if (response.status === 401) {
732 const body = await response.json();
733
734 if (body.code === 'TOKEN_EXPIRED') {
735 await this.refreshToken();
736
737 // Retry original request
738 return fetch(url, {
739 ...options,
740 headers: {
741 ...options.headers,
742 'Authorization': `Bearer ${this.accessToken}`
743 }
744 });
745 }
746 }
747
748 return response;
749 }
750
751 async logout() {
752 await fetch('/auth/logout', {
753 method: 'POST',
754 credentials: 'include'
755 });
756
757 this.accessToken = null;
758 }
759}
760
761export const auth = new AuthManager();
762```
763
764Don't store access tokens in `localStorage`, they're readable by any XSS payload. In-memory (as above) plus an httpOnly refresh cookie is the standard shape. For SPAs that need to survive a page refresh, use the BroadcastChannel API to share the in-memory token across tabs and accept that a hard refresh forces a `/auth/refresh` call.
765
766## Passkeys / WebAuthn
767
768WebAuthn L3 is at W3C Candidate Recommendation Snapshot as of 2026-01-13 (https://www.w3.org/TR/webauthn-3/). Comments accepted through 2026-02-10. CTAP 2.3 became a FIDO Alliance Proposed Standard 2026-02-26.
769
770Recommended libraries:
771
772- **Node:** `@simplewebauthn/server` (current 13.3.0). Companion browser package: `@simplewebauthn/browser`.
773- **Python:** `webauthn` on PyPI (current 2.7.1). Note: the GitHub repo is `duo-labs/py_webauthn`, but the install command is `pip install webauthn`, the PyPI package name is `webauthn`, NOT `py_webauthn`.
774
775### Registration ceremony
776
777```javascript
778// Node, @simplewebauthn/server
779const {
780 generateRegistrationOptions,
781 verifyRegistrationResponse,
782} = require('@simplewebauthn/server');
783
784const RP_ID = 'yourapp.com'; // your effective domain
785const RP_NAME = 'YourApp';
786const ORIGIN = 'https://yourapp.com';
787
788// 1. Server: build options for the browser
789app.post('/auth/passkey/register/options', requireAuth(), async (req, res) => {
790 const user = await db.query('SELECT id, email, name FROM users WHERE id = $1', [req.userId]);
791 const existing = await db.query(
792 'SELECT credential_id, transports FROM passkeys WHERE user_id = $1',
793 [req.userId]
794 );
795
796 const options = await generateRegistrationOptions({
797 rpName: RP_NAME,
798 rpID: RP_ID,
799 userID: Buffer.from(String(user.rows[0].id)),
800 userName: user.rows[0].email,
801 userDisplayName: user.rows[0].name,
802 attestationType: 'none',
803 excludeCredentials: existing.rows.map(c => ({
804 id: c.credential_id,
805 transports: c.transports || undefined,
806 })),
807 authenticatorSelection: {
808 residentKey: 'preferred', // discoverable credentials enable conditional UI
809 userVerification: 'preferred',
810 },
811 });
812
813 // Store challenge for the verify step (Redis with short TTL)
814 await redisClient.setEx(
815 `webauthn:reg:${req.userId}`,
816 300,
817 options.challenge
818 );
819
820 res.json(options);
821});
822
823// 2. Server: verify what the browser returned
824app.post('/auth/passkey/register/verify', requireAuth(), async (req, res) => {
825 const expectedChallenge = await redisClient.get(`webauthn:reg:${req.userId}`);
826
827 let verification;
828 try {
829 verification = await verifyRegistrationResponse({
830 response: req.body,
831 expectedChallenge,
832 expectedOrigin: ORIGIN,
833 expectedRPID: RP_ID,
834 requireUserVerification: false,
835 });
836 } catch (err) {
837 return res.status(400).json({ error: err.message });
838 }
839
840 if (!verification.verified || !verification.registrationInfo) {
841 return res.status(400).json({ error: 'Registration not verified' });
842 }
843
844 const { credential, credentialBackedUp, credentialDeviceType } =
845 verification.registrationInfo;
846
847 await db.query(
848 `INSERT INTO passkeys
849 (user_id, credential_id, public_key, counter, transports, device_type, backed_up)
850 VALUES ($1, $2, $3, $4, $5, $6, $7)`,
851 [
852 req.userId,
853 credential.id,
854 credential.publicKey,
855 credential.counter,
856 req.body.response?.transports || null,
857 credentialDeviceType,
858 credentialBackedUp,
859 ]
860 );
861
862 await redisClient.del(`webauthn:reg:${req.userId}`);
863 res.json({ verified: true });
864});
865```
866
867Install and bundle the browser helper locally. Commit the lockfile and generated
868asset, and verify its checksum during deployment. If the module code remains
869inline as in the examples below, generate a fresh nonce for every response and
870send a CSP such as `script-src 'self' 'nonce-{{CSP_NONCE}}'`; replace the
871placeholder in both the header and tag, and never reuse a nonce. Alternatively,
872move the module code into a same-origin external file and use `script-src
873'self'` without a nonce. A remote module graph cannot be secured by adding SRI
874to only its first import.
875
876```bash
877npm install --save-exact @simplewebauthn/browser@13.3.0
878npm install --save-dev --save-exact esbuild@0.28.1
879npm ci
880mkdir -p public/vendor
881npx esbuild @simplewebauthn/browser --bundle --format=esm --platform=browser \
882 --outfile=public/vendor/simplewebauthn-browser-13.3.0.mjs
883sha256sum public/vendor/simplewebauthn-browser-13.3.0.mjs \
884 > public/vendor/SHA256SUMS
885sha256sum -c public/vendor/SHA256SUMS
886```
887
888```html
889<!-- Browser, local @simplewebauthn/browser bundle -->
890<script type="module" nonce="{{CSP_NONCE}}">
891 import { startRegistration }
892 from '/vendor/simplewebauthn-browser-13.3.0.mjs';
893
894 async function enrollPasskey() {
895 const optsRes = await fetch('/auth/passkey/register/options', { method: 'POST', credentials: 'include' });
896 const options = await optsRes.json();
897
898 const attResp = await startRegistration({ optionsJSON: options });
899
900 const verRes = await fetch('/auth/passkey/register/verify', {
901 method: 'POST',
902 credentials: 'include',
903 headers: { 'Content-Type': 'application/json' },
904 body: JSON.stringify(attResp),
905 });
906 return verRes.json();
907 }
908
909 document.getElementById('enroll').addEventListener('click', enrollPasskey);
910</script>
911```
912
913### Authentication ceremony (with conditional UI)
914
915Conditional UI lets the browser surface passkeys directly inside the username autofill dropdown, the user picks a passkey from the same UI they'd use to autofill an email.
916
917```javascript
918// Node, server side
919const {
920 generateAuthenticationOptions,
921 verifyAuthenticationResponse,
922} = require('@simplewebauthn/server');
923
924app.post('/auth/passkey/login/options', async (req, res) => {
925 const options = await generateAuthenticationOptions({
926 rpID: RP_ID,
927 userVerification: 'preferred',
928 // allowCredentials omitted → discoverable credentials → conditional UI works
929 });
930
931 // Tie the challenge to a temporary session marker
932 const challengeId = crypto.randomBytes(16).toString('hex');
933 await redisClient.setEx(`webauthn:auth:${challengeId}`, 300, options.challenge);
934 res.json({ options, challengeId });
935});
936
937app.post('/auth/passkey/login/verify', async (req, res) => {
938 const { challengeId, response } = req.body;
939 const expectedChallenge = await redisClient.get(`webauthn:auth:${challengeId}`);
940
941 if (!expectedChallenge) {
942 return res.status(400).json({ error: 'Challenge expired' });
943 }
944
945 const credentialId = response.id;
946 const stored = await db.query(
947 `SELECT user_id, public_key, counter, transports FROM passkeys WHERE credential_id = $1`,
948 [credentialId]
949 );
950 if (stored.rows.length === 0) {
951 return res.status(401).json({ error: 'Unknown credential' });
952 }
953
954 let verification;
955 try {
956 verification = await verifyAuthenticationResponse({
957 response,
958 expectedChallenge,
959 expectedOrigin: ORIGIN,
960 expectedRPID: RP_ID,
961 credential: {
962 id: credentialId,
963 publicKey: stored.rows[0].public_key,
964 counter: stored.rows[0].counter,
965 transports: stored.rows[0].transports || undefined,
966 },
967 requireUserVerification: false,
968 });
969 } catch (err) {
970 return res.status(401).json({ error: err.message });
971 }
972
973 if (!verification.verified) {
974 return res.status(401).json({ error: 'Authentication not verified' });
975 }
976
977 // Persist new counter
978 await db.query(
979 `UPDATE passkeys SET counter = $1, last_used_at = NOW() WHERE credential_id = $2`,
980 [verification.authenticationInfo.newCounter, credentialId]
981 );
982
983 // Issue session/tokens as usual
984 req.session.regenerate(() => {
985 req.session.userId = stored.rows[0].user_id;
986 res.json({ verified: true });
987 });
988});
989```
990
991```html
992<!-- Browser, discoverable credential + conditional UI -->
993<input type="email" name="email" autocomplete="username webauthn">
994<script type="module" nonce="{{CSP_NONCE}}">
995 import { startAuthentication, browserSupportsWebAuthnAutofill }
996 from '/vendor/simplewebauthn-browser-13.3.0.mjs';
997
998 if (await browserSupportsWebAuthnAutofill()) {
999 const optsRes = await fetch('/auth/passkey/login/options', { method: 'POST' });
1000 const { options, challengeId } = await optsRes.json();
1001
1002 const authResp = await startAuthentication({
1003 optionsJSON: options,
1004 useBrowserAutofill: true, // conditional UI
1005 });
1006
1007 await fetch('/auth/passkey/login/verify', {
1008 method: 'POST',
1009 credentials: 'include',
1010 headers: { 'Content-Type': 'application/json' },
1011 body: JSON.stringify({ challengeId, response: authResp }),
1012 });
1013 location.href = '/dashboard';
1014 }
1015</script>
1016```
1017
1018### WebAuthn L3 signal methods
1019
1020L3 adds `PublicKeyCredential` static methods so the relying party can keep syncable passkeys aligned with server state without forcing a re-enrollment:
1021
1022- `signalUnknownCredential({ rpId, credentialId })`, call after a verify attempt against a credential the server no longer knows about. The authenticator hides it from the user's account-picker UI.
1023- `signalAllAcceptedCredentials({ rpId, userId, allAcceptedCredentialIds })`, call after the server's credential list changes (revoke, enroll). The authenticator prunes anything not on the list.
1024- `signalCurrentUserDetails({ rpId, userId, name, displayName })`, call after profile changes. The authenticator updates labels in the picker UI.
1025
1026These are advisory and best-effort; treat them as housekeeping, not security boundaries.
1027
1028### When to use `webauthn` (Python)
1029
1030```python
1031# pip install webauthn # PyPI package name is `webauthn`, NOT py_webauthn
1032from webauthn import (
1033 generate_registration_options,
1034 verify_registration_response,
1035 generate_authentication_options,
1036 verify_authentication_response,
1037)
1038from webauthn.helpers.structs import (
1039 AuthenticatorSelectionCriteria,
1040 ResidentKeyRequirement,
1041 UserVerificationRequirement,
1042)
1043
1044RP_ID = "yourapp.com"
1045RP_NAME = "YourApp"
1046ORIGIN = "https://yourapp.com"
1047
1048options = generate_registration_options(
1049 rp_id=RP_ID,
1050 rp_name=RP_NAME,
1051 user_id=str(user_id).encode(),
1052 user_name=user_email,
1053 authenticator_selection=AuthenticatorSelectionCriteria(
1054 resident_key=ResidentKeyRequirement.PREFERRED,
1055 user_verification=UserVerificationRequirement.PREFERRED,
1056 ),
1057)
1058```
1059
1060## Password reset flow
1061
1062### Secure implementation
1063
1064```javascript
1065const crypto = require('crypto');
1066
1067// Request password reset
1068app.post('/auth/forgot-password', async (req, res) => {
1069 const { email } = req.body;
1070
1071 // Always return success to prevent email enumeration
1072 res.json({ message: 'If an account exists, a reset link has been sent.' });
1073
1074 // Find user (async, after response)
1075 const result = await db.query(
1076 'SELECT id FROM users WHERE email = $1',
1077 [email.toLowerCase()]
1078 );
1079
1080 if (result.rows.length === 0) {
1081 return; // User doesn't exist, but don't reveal that
1082 }
1083
1084 const user = result.rows[0];
1085
1086 // Generate secure token
1087 const token = crypto.randomBytes(32).toString('hex');
1088 const tokenHash = crypto.createHash('sha256').update(token).digest('hex');
1089 const expiresAt = new Date(Date.now() + 3600000); // 1 hour
1090
1091 // Store hashed token (not plain token)
1092 await db.query(
1093 'INSERT INTO password_resets (user_id, token_hash, expires_at) VALUES ($1, $2, $3)',
1094 [user.id, tokenHash, expiresAt]
1095 );
1096
1097 // Send email with plain token
1098 const resetUrl = `https://yourapp.com/reset-password?token=${token}`;
1099 await sendEmail(email, 'Password Reset', `Reset your password: ${resetUrl}`);
1100});
1101
1102// Reset password
1103app.post('/auth/reset-password', async (req, res) => {
1104 const { token, newPassword } = req.body;
1105
1106 if (!token || !newPassword) {
1107 return res.status(400).json({ error: 'Token and new password required' });
1108 }
1109
1110 // NIST 800-63B-4: 15-char minimum
1111 if (newPassword.length < 15) {
1112 return res.status(400).json({ error: 'Password must be at least 15 characters' });
1113 }
1114
1115 if (await isPwned(newPassword)) {
1116 return res.status(400).json({ error: 'This password has appeared in a known breach. Choose a different one.' });
1117 }
1118
1119 // Hash the provided token to compare with stored hash
1120 const tokenHash = crypto.createHash('sha256').update(token).digest('hex');
1121
1122 // Find valid reset token
1123 const result = await db.query(
1124 `SELECT user_id FROM password_resets
1125 WHERE token_hash = $1 AND expires_at > NOW() AND used = false`,
1126 [tokenHash]
1127 );
1128
1129 if (result.rows.length === 0) {
1130 return res.status(400).json({ error: 'Invalid or expired token' });
1131 }
1132
1133 const userId = result.rows[0].user_id;
1134
1135 // Hash new password with argon2id
1136 const hashedPassword = await argon2.hash(newPassword, ARGON2_OPTS);
1137
1138 // Update password and invalidate token
1139 await db.query('UPDATE users SET password_hash = $1 WHERE id = $2', [hashedPassword, userId]);
1140 await db.query('UPDATE password_resets SET used = true WHERE token_hash = $1', [tokenHash]);
1141
1142 // Invalidate all existing sessions and refresh-token families for this user
1143 await db.query('DELETE FROM sessions WHERE user_id = $1', [userId]);
1144 // (also revoke all refresh-token families for the user in your token store)
1145
1146 res.json({ success: true });
1147});
1148```
1149
1150## OAuth 2.1 (with Google example)
1151
1152OAuth 2.1 is currently `draft-ietf-oauth-v2-1-15` dated 2026-03-02 (https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-15). Not yet an RFC, but providers (Google, Microsoft, Okta, Auth0) already implement these constraints today, so design to the 2.1 baseline.
1153
1154### What 2.1 requires (and removes)
1155
1156- **PKCE mandatory for ALL clients, including confidential clients.** S256 only, `plain` is deprecated.
1157- **Exact-string redirect-URI matching.** No prefix or wildcard matching.
1158- **No implicit grant (`response_type=token`).** Use authorization code with PKCE.
1159- **No Resource Owner Password Credentials (ROPC).** First-party login flows go through the authorization endpoint.
1160- **Bearer tokens never in URL query strings.** Always Authorization header.
1161
1162### Server-side code-with-PKCE flow (Google)
1163
1164```javascript
1165const { OAuth2Client } = require('google-auth-library');
1166const crypto = require('crypto');
1167
1168const oauth2Client = new OAuth2Client(
1169 process.env.GOOGLE_CLIENT_ID,
1170 process.env.GOOGLE_CLIENT_SECRET,
1171 process.env.GOOGLE_REDIRECT_URI
1172);
1173
1174function pkcePair() {
1175 const verifier = crypto.randomBytes(32).toString('base64url');
1176 const challenge = crypto.createHash('sha256').update(verifier).digest('base64url');
1177 return { verifier, challenge };
1178}
1179
1180// Step 1: Redirect to Google
1181app.get('/auth/google', (req, res) => {
1182 const state = crypto.randomBytes(32).toString('hex');
1183 const { verifier, challenge } = pkcePair();
1184
1185 req.session.oauthState = state;
1186 req.session.oauthVerifier = verifier;
1187
1188 const authUrl = oauth2Client.generateAuthUrl({
1189 access_type: 'offline',
1190 scope: ['email', 'profile'],
1191 state,
1192 prompt: 'consent',
1193 code_challenge: challenge,
1194 code_challenge_method: 'S256',
1195 });
1196
1197 res.redirect(authUrl);
1198});
1199
1200// Step 2: Handle callback
1201app.get('/auth/google/callback', async (req, res) => {
1202 const { code, state } = req.query;
1203
1204 // Verify state to prevent CSRF
1205 if (!state || state !== req.session.oauthState) {
1206 return res.status(400).send('Invalid state parameter');
1207 }
1208
1209 const verifier = req.session.oauthVerifier;
1210 delete req.session.oauthState;
1211 delete req.session.oauthVerifier;
1212
1213 if (!verifier) {
1214 return res.status(400).send('Missing PKCE verifier');
1215 }
1216
1217 try {
1218 // Exchange code for tokens, include the PKCE verifier
1219 const { tokens } = await oauth2Client.getToken({
1220 code,
1221 codeVerifier: verifier,
1222 });
1223 oauth2Client.setCredentials(tokens);
1224
1225 // Validate the id_token: Google verifies signature; we MUST check audience
1226 const ticket = await oauth2Client.verifyIdToken({
1227 idToken: tokens.id_token,
1228 audience: process.env.GOOGLE_CLIENT_ID,
1229 });
1230
1231 const payload = ticket.getPayload();
1232 if (payload.iss !== 'https://accounts.google.com' && payload.iss !== 'accounts.google.com') {
1233 return res.status(400).send('Unexpected issuer');
1234 }
1235
1236 const { sub: googleId, email, name, picture } = payload;
1237
1238 // Find or create user
1239 let user = await db.query('SELECT id FROM users WHERE google_id = $1', [googleId]);
1240
1241 if (user.rows.length === 0) {
1242 user = await db.query(
1243 `INSERT INTO users (google_id, email, name, avatar_url)
1244 VALUES ($1, $2, $3, $4) RETURNING id`,
1245 [googleId, email, name, picture]
1246 );
1247 }
1248
1249 // Create session
1250 req.session.regenerate((err) => {
1251 if (err) {
1252 return res.status(500).send('Session error');
1253 }
1254 req.session.userId = user.rows[0].id;
1255 res.redirect('/dashboard');
1256 });
1257
1258 } catch (error) {
1259 console.error('OAuth error:', error);
1260 res.status(400).send('Authentication failed');
1261 }
1262});
1263```
1264
1265The same pattern applies to any OAuth 2.1 / OIDC provider, substitute issuer, client, scopes, and the userinfo lookup. Confirm exact-string redirect URIs in the provider console match what your server sends.
1266
1267## MFA (passkey-first)
1268
1269CISA "Implementing Phishing-Resistant MFA" (2022-10-31, still current 2026-05; https://www.cisa.gov/sites/default/files/publications/fact-sheet-implementing-phishing-resistant-mfa-508c.pdf) ranks factor strength:
1270
1271- **Phishing-resistant tier:** FIDO2 / WebAuthn (passkeys), PKI smartcards (PIV/CAC). Required at NIST AAL3.
1272- **AAL2-acceptable, not phishing-resistant:** App-based push with number matching, TOTP via authenticator app.
1273- **Restricted, last resort:** SMS / voice OTP. NIST 800-63B-4 §5 explicitly restricts these.
1274
1275In 2026: **don't add SMS as a new factor.** Migrate users off it where you can.
1276
1277### Passkey-as-second-factor
1278
1279If passwords are still your first factor, a registered passkey is the strongest second factor available. The registration and authentication ceremonies in the Passkeys / WebAuthn section above work unchanged, gate `/auth/login` on a successful passkey verify after password verify.
1280
1281### TOTP (still valid for AAL2)
1282
1283```javascript
1284const speakeasy = require('speakeasy');
1285const QRCode = require('qrcode');
1286
1287// Enable MFA for user
1288app.post('/auth/mfa/enable', requireAuth(), async (req, res) => {
1289 // Generate secret
1290 const secret = speakeasy.generateSecret({
1291 name: `YourApp:${req.user.email}`,
1292 issuer: 'YourApp'
1293 });
1294
1295 // Store secret (encrypted) temporarily until verified
1296 await db.query(
1297 'UPDATE users SET mfa_secret_temp = $1 WHERE id = $2',
1298 [encrypt(secret.base32), req.userId]
1299 );
1300
1301 // Generate QR code
1302 const qrCode = await QRCode.toDataURL(secret.otpauth_url);
1303
1304 res.json({
1305 secret: secret.base32, // Show this as backup
1306 qrCode: qrCode
1307 });
1308});
1309
1310// Verify and activate MFA
1311app.post('/auth/mfa/verify', requireAuth(), async (req, res) => {
1312 const { code } = req.body;
1313
1314 const result = await db.query(
1315 'SELECT mfa_secret_temp FROM users WHERE id = $1',
1316 [req.userId]
1317 );
1318
1319 const secret = decrypt(result.rows[0].mfa_secret_temp);
1320
1321 const verified = speakeasy.totp.verify({
1322 secret: secret,
1323 encoding: 'base32',
1324 token: code,
1325 window: 1 // Allow 1 step tolerance
1326 });
1327
1328 if (!verified) {
1329 return res.status(400).json({ error: 'Invalid code' });
1330 }
1331
1332 // Move secret from temp to permanent
1333 await db.query(
1334 'UPDATE users SET mfa_secret = mfa_secret_temp, mfa_secret_temp = NULL, mfa_enabled = true WHERE id = $1',
1335 [req.userId]
1336 );
1337
1338 res.json({ success: true });
1339});
1340
1341// Login with MFA
1342app.post('/auth/login', async (req, res) => {
1343 const { email, password, mfaCode } = req.body;
1344
1345 // ... verify email/password first ...
1346
1347 if (user.mfa_enabled) {
1348 if (!mfaCode) {
1349 return res.status(401).json({
1350 error: 'MFA code required',
1351 requiresMfa: true
1352 });
1353 }
1354
1355 const verified = speakeasy.totp.verify({
1356 secret: decrypt(user.mfa_secret),
1357 encoding: 'base32',
1358 token: mfaCode,
1359 window: 1
1360 });
1361
1362 if (!verified) {
1363 return res.status(401).json({ error: 'Invalid MFA code' });
1364 }
1365 }
1366
1367 // ... create session/token ...
1368});
1369```
1370
1371### SMS: don't add it as a new factor in 2026
1372
1373If you already have SMS in production, plan its retirement. Snowflake (see breach lessons) and the broader SIM-swap landscape make SMS a liability, not a safeguard. NIST 800-63B-4 §5 restricts it; CISA recommends moving off it.
1374
1375## Common breach lessons
1376
1377Vignettes anchoring patterns to actual incidents. Each is a 2-3 sentence summary plus the lesson encoded in the recipes above.
1378
1379### Change Healthcare ransomware (Feb 2024)
1380
1381Attackers used compromised credentials on a Citrix remote-access portal that lacked MFA. Disruption ran for weeks; UnitedHealth Group disclosed an approximately $22M ransom and exposure of records for roughly 1 in 3 US patients. Per the UnitedHealth Group RCA at https://www.unitedhealthgroup.com/newsroom/2024/2024-04-22-uhg-update-on-change-healthcare-cyberattack.html.
1382
1383**Lesson:** MFA on every remote-access portal, VPN, Citrix, RDP gateway, jump host, not just user-facing apps. The "internal" portal is the one attackers target precisely because it's less guarded.
1384
1385### Snowflake / UNC5537 (Apr-Jun 2024)
1386
1387Approximately 165 customer tenants were breached because Snowflake's MFA was opt-in per tenant; attackers used infostealer-harvested credentials against accounts with no second factor. Mandiant's writeup is at https://cloud.google.com/blog/topics/threat-intelligence/unc5537-snowflake-data-theft-extortion. Snowflake enforced default-on MFA from October 2024 and has been phasing in mandatory blocking of password-only sign-in across 2025-2026; see Snowflake's MFA enforcement documentation (https://docs.snowflake.com/) for the current rollout schedule.
1388
1389**Lesson:** MFA must default to ON, not opt-in. If your customers can disable it, attackers will find the ones who did.
1390
1391### Storm-0558 (CSRB review, 2024-04)
1392
1393A Microsoft consumer signing key was compromised; attackers forged Azure AD tokens and accessed enterprise OWA mailboxes. The proximate failure was that OWA's token-validation library accepted a consumer-key-signed token for enterprise mailboxes, it skipped scope, issuer, and signing-key tenancy validation. CSRB report: https://www.cisa.gov/resources-tools/resources/CSRB-Review-Summer-2023-MEO-Intrusion. (Microsoft's MSRC postmortem URL is decommissioned.)
1394
1395**Lesson:** Validate every claim every time, issuer, audience, scope, expiration, pinned algorithm. AND for multi-issuer / OIDC deployments, validate signing-key tenancy: pin which JWKS each trusted issuer is allowed to use, and never select a verifying key from a different issuer's set, even if the `kid` matches. The JWT recipe above bakes in `iss` / `aud` / `scope` / pinned algorithm, that's the claim-level half of the lesson and covers single-issuer private-token deployments. The signing-key tenancy half (JWKS resolution and issuer-to-key-set binding) is not in the sample; see the comment block above the `requireAuth` function for what to add when accepting tokens from multiple tenants.
1396
1397### Okta HAR breach (Oct 2023)
1398
1399Customers uploaded HAR (HTTP Archive) debug files to Okta support; the files contained live session tokens. Five customer sessions were hijacked. Per Okta's writeup at https://sec.okta.com/articles/harfiles/.
1400
1401**Lesson:** Sanitize session tokens and other bearer credentials at log boundaries. HAR uploads, error reports, debug dumps, strip Authorization headers, set-cookie, and known token-shaped values before they leave the user's browser.
1402
1403### 23andMe credential stuffing (Oct 2023, settled 2024)
1404
1405Attackers credential-stuffed approximately 14,000 accounts using passwords reused from other breaches, then traversed the DNA Relatives social graph to expose data on roughly 6.9 million users.
1406
1407**Lesson:** Per-account read quotas on relationship and graph endpoints, not just per-IP rate limits. A single compromised account should not be able to enumerate the social graph faster than a human user reasonably would. Pwned-password screening (HIBP) at registration and password-reset blocks the inbound vector entirely.
1408
1409## Security considerations checklist
1410
1411NIST AAL terminology in parentheses where relevant.
1412
1413### Password storage
1414- [ ] Default is argon2id with one of OWASP's 5 equivalent profiles (m=47104/t=1, m=19456/t=2, m=12288/t=3, m=9216/t=4, m=7168/t=5; all p=1)
1415- [ ] If using bcrypt, cost 10 minimum; pre-hash inputs over 72 bytes with SHA-256 (or reject)
1416- [ ] PBKDF2 only when FIPS-140 compliance is required
1417- [ ] Never storing plain-text passwords
1418- [ ] Never logging passwords (including in error handlers)
1419
1420### Password policy (NIST SP 800-63B-4)
1421- [ ] 15-character minimum for single-factor; 8-char minimum for multi-factor
1422- [ ] 64-character minimum maximum (verifier accepts at least 64)
1423- [ ] No composition rules ("SHALL NOT impose")
1424- [ ] Unicode and paste allowed
1425- [ ] No periodic rotation
1426- [ ] Verifier checks against breach blocklist (HIBP k-anonymity or equivalent)
1427
1428### Session management
1429- [ ] Sessions stored server-side (not just in cookies)
1430- [ ] Session IDs are cryptographically random
1431- [ ] Sessions regenerated on login AND on privilege change
1432- [ ] Sessions invalidated on logout AND on password reset
1433- [ ] Sessions have a maximum lifetime
1434- [ ] Cookies set `httpOnly`, `secure` in prod, `sameSite=lax` or stricter
1435
1436### JWT security
1437- [ ] Short access-token lifetime (15 min or less)
1438- [ ] Refresh tokens stored as httpOnly cookies
1439- [ ] Refresh-token rotation with reuse detection (rotated token used twice → revoke entire family)
1440- [ ] Token revocation mechanism exists
1441- [ ] Secrets are at least 256 bits
1442- [ ] Full validation on every request: issuer, audience, expiration, scope, algorithm pinned (no `alg=none`), signing-key tenancy (Storm-0558)
1443- [ ] Bound tokens (DPoP per RFC 9449 or mTLS per RFC 8705) for high-value APIs
1444
1445### Passkeys / WebAuthn
1446- [ ] Registration ceremony validates challenge, origin, and RP ID
1447- [ ] Authentication ceremony validates challenge, origin, RP ID, and signature counter
1448- [ ] Discoverable credentials enabled (`residentKey: 'preferred'`) for conditional UI
1449- [ ] WebAuthn L3 signal methods called when server credential state changes
1450- [ ] CTAP 2.3 considered when picking authenticator policy
1451
1452### MFA (CISA tier ranks)
1453- [ ] Phishing-resistant tier (FIDO2/WebAuthn, PIV/CAC) for AAL3 contexts
1454- [ ] App-based push with number matching or TOTP for AAL2
1455- [ ] No new SMS factors in 2026; migrate existing users off SMS
1456- [ ] MFA defaults to ON, not opt-in (Snowflake lesson)
1457- [ ] MFA enforced on every remote-access portal (Change Healthcare lesson)
1458
1459### OAuth 2.1
1460- [ ] PKCE with S256 on all clients, including confidential
1461- [ ] Exact-string redirect-URI matching
1462- [ ] No implicit or ROPC grants
1463- [ ] State parameter validated on callback
1464- [ ] `id_token` audience and issuer validated
1465
1466### Rate limiting
1467- [ ] Login attempts limited per IP and per account
1468- [ ] Account lockout after N failures
1469- [ ] Password reset requests limited
1470- [ ] MFA verification attempts limited
1471- [ ] Per-account quotas on relationship / graph endpoints (23andMe lesson)
1472
1473### CSRF protection
1474- [ ] SameSite cookie attribute set
1475- [ ] CSRF tokens for state-changing operations
1476- [ ] OAuth state parameter verified
1477
1478### Information disclosure
1479- [ ] Same error messages for valid / invalid users
1480- [ ] Timing attacks mitigated (dummy hash compare on missing user)
1481- [ ] No user enumeration via registration / reset
1482- [ ] Bearer tokens stripped from log boundaries (Okta HAR lesson)