Auth Systems and Security Picture Book
outside You DoorauthN inside · authZ per room Lobby ✔ Files ✔ Vault ✘ Admin ✘ Who are you? · What may you do? two different questions, answered at two different steps
PLATE 0 — Authentication checks identity. Authorization checks permission.
A picture book for grown-ups · with code

Auth Systems and Application Security

Nine spreads on how logins, sessions, tokens, OAuth and permissions work, and the attacks that target them, with Node.js examples you can adapt.

Say it like a pro

"Argon2id hashes, httpOnly session cookies, MFA, deny-by-default RBAC checked on the server, CSRF and CSP protections, and logs for every auth event."

Defensive focus: how to build it right and test your own apps. Use the tabs or the ← → keys.

✘ plaintextpassword = "hunter2" → one breach exposes everyone ✘ fast hash (MD5, SHA-256)billions of guesses per second on a GPU ✔ slow, salted hashargon2id · bcrypt · scrypt: tuned to ~100–500 ms per check stored: $argon2id$v=19$m=65536,t=3,p=4$<salt>$<hash> salt is random per user and stored with the hash
PLATE 1 — A good password hash is deliberately slow, so guessing is expensive.
Chapter 1 · Passwords

Never store them, only prove you can verify them

// npm i argon2
const argon2 = require('argon2');

// signup
const hash = await argon2.hash(password, { type: argon2.argon2id });
await db.query('INSERT INTO users (email, pw_hash) VALUES ($1,$2)', [email, hash]);

// login
const user = (await db.query('SELECT * FROM users WHERE email=$1', [email])).rows[0];
const ok = user ? await argon2.verify(user.pw_hash, password) : await argon2.verify(DUMMY_HASH, password);
if (!user || !ok) return res.status(401).json({ error: 'Invalid email or password' });  // same message either way
if (argon2.needsRehash(user.pw_hash)) { /* upgrade the hash silently */ }
  • Length over complexity: allow 12+ characters (and long passphrases, up to 64+). Drop forced symbols and rotation.
  • Check against breached passwords (Have I Been Pwned's k-anonymity API).
  • Rate-limit and lock out gently per account and per IP.
  • Reset flow: single-use, short-lived, random token; email only the link; invalidate old sessions after.
Say it like a pro

"Argon2id with a per-user salt, constant-time verify, identical error messages, and breach-checked passphrases."

Server session cookie: sid=9f2… session store ID is meaningless; data lives server-side ✔ revoke instantly (delete the row) ✔ small, simple, hard to misuse ✘ needs a shared store when scaled out JWT access token header.payload.signature claims are inside, signed (not hidden) ✔ any server can verify, no lookup ✘ hard to revoke before expiry ✘ easy to get wrong (alg, storage) A sound default for a normal web app server-side session · cookie: HttpOnly; Secure; SameSite=Lax tokens (short-lived JWT + rotating refresh) for APIs and mobile rotate the session ID on login · expire idle and absolute
PLATE 2 — After login, something has to prove "it's still me". Pick it deliberately.
Chapter 2 · Sessions & tokens

Staying logged in without staying hackable

// npm i express-session connect-redis redis
app.set('trust proxy', 1);
app.use(session({
  store: new RedisStore({ client: redis }),
  name: 'sid',
  secret: process.env.SESSION_SECRET,
  resave: false, saveUninitialized: false,
  rolling: true,
  cookie: {
    httpOnly: true,          // JavaScript can't read it → XSS can't steal it
    secure: true,            // HTTPS only
    sameSite: 'lax',         // blunts CSRF
    maxAge: 1000 * 60 * 30,  // 30 min idle
  },
}));

// on successful login: new ID prevents session fixation
req.session.regenerate(() => { req.session.userId = user.id; res.json({ ok: true }); });
// logout: destroy server-side too
req.session.destroy(() => res.clearCookie('sid').sendStatus(204));
localStorage
readable by any script on the page; avoid storing long-lived tokens there
refresh token
long-lived, stored httpOnly, rotated on every use; revoke the family if reuse is detected
Say it like a pro

"HttpOnly, Secure, SameSite cookies, regenerate on login, and server-side revocation."

header{"alg":"RS256"} payload (claims)sub · exp · iss · aud signatureHMAC / RSA .. Verify, don't just decode 1 · signature valid with a key you trust 2 · alg is the one you expect (never accept "none") 3 · exp not passed · nbf ok 4 · iss is your issuer · aud is this API Classic mistakes alg confusion (RS256 → HS256 with the public key as secret) trusting unverified claims · very long expiry · secrets in payload no way to revoke · weak HMAC secret
PLATE 3 — A JWT is a signed note. Anyone can read it. Only the key holder can forge it.
Chapter 3 · JSON Web Tokens

Use them carefully, or don't use them

// npm i jose
const { SignJWT, jwtVerify } = require('jose');
const key = new TextEncoder().encode(process.env.JWT_SECRET);   // ≥ 32 random bytes

const token = await new SignJWT({ role: user.role })
  .setProtectedHeader({ alg: 'HS256' })
  .setSubject(String(user.id))
  .setIssuer('https://api.example.com')
  .setAudience('example-web')
  .setIssuedAt()
  .setExpirationTime('10m')              // short!
  .sign(key);

// verify with explicit expectations
try {
  const { payload } = await jwtVerify(token, key, {
    algorithms: ['HS256'],
    issuer: 'https://api.example.com',
    audience: 'example-web',
  });
  req.user = { id: payload.sub, role: payload.role };
} catch { return res.sendStatus(401); }
$ openssl rand -base64 48        # generate a strong signing secret
HS256 vs RS256
shared secret vs key pair; use asymmetric when many services verify but only one issues
JWKS
published public keys, so verifiers can rotate keys safely (kid)
Say it like a pro

"Pinned algorithm, validated iss, aud and exp, ten-minute lifetime, and rotating refresh tokens."

App IdentityProvider App server 1 redirect + challenge 3 code 4 code + verifier → backend 5 token request 2 user signs in + consents Vocabulary that gets mixed up OAuth 2.0 → delegated authorization: "let this app read my calendar" OpenID Connect → adds authentication: an ID token says who logged in SAML → older enterprise SSO, XML-based use a library or hosted provider (Auth0, Clerk, Keycloak, Cognito) don't write your own OAuth server unless it's your product
PLATE 4 — "Sign in with Google": your app never sees the user's password.
Chapter 4 · OAuth 2.0, OIDC & SSO

Let someone else do the login

  1. App redirects the user to the provider with client_id, redirect_uri, scope, a random state, and a PKCE code_challenge.
  2. User authenticates (with MFA) and consents.
  3. Provider redirects back with a one-time code.
  4. Your backend swaps code + code_verifier for tokens, over TLS.
  5. Validate the ID token (signature, iss, aud, nonce), then create your own session.
// Express + openid-client (sketch)
const { Issuer, generators } = require('openid-client');
const issuer = await Issuer.discover('https://accounts.example-idp.com');
const client = new issuer.Client({ client_id, client_secret, redirect_uris: [CB], response_types: ['code'] });

app.get('/login', (req, res) => {
  req.session.verifier = generators.codeVerifier();
  req.session.state    = generators.state();
  res.redirect(client.authorizationUrl({
    scope: 'openid email profile', state: req.session.state,
    code_challenge: generators.codeChallenge(req.session.verifier), code_challenge_method: 'S256',
  }));
});
state
stops login-CSRF; must match on return
redirect_uri
exact-match allowlist, or codes leak to attackers
scopes
ask for the minimum
Say it like a pro

"Authorization code flow with PKCE, exact redirect URIs, state and nonce checked, minimal scopes."

Passkeys / FIDO2 keys Authenticator app (TOTP) Push approval SMS / email codes stronger Passkey login device private keystays here signs a challenge bound to your domain Why passkeys beat passwords nothing to phish or reuse: the signature only works on the real site nothing secret on your server to leak (only public keys)
PLATE 5 — A second factor stops most account takeovers. Phishing-resistant ones stop nearly all.
Chapter 5 · MFA & passkeys

Something you know, plus something you have

// TOTP (authenticator app codes), npm i otplib qrcode
const { authenticator } = require('otplib');

// enrol: store the secret encrypted, show a QR once
const secret = authenticator.generateSecret();
const uri = authenticator.keyuri(user.email, 'MyApp', secret);   // → QR code
// confirm setup by verifying a first code before enabling
authenticator.check(codeFromUser, secret);                       // true/false

// also: generate ~10 single-use recovery codes (store only their hashes)
// Passkeys (WebAuthn) in the browser
const cred = await navigator.credentials.create({ publicKey: optionsFromServer });
// POST cred to the server; verify with @simplewebauthn/server and store the public key
  • Prefer passkeys or security keys for admins and high-value accounts.
  • Rate-limit code attempts; codes are 6 digits, so unlimited tries break them.
  • Plan recovery carefully; account recovery is a favourite attack path.
  • Require re-authentication for sensitive actions (change email, add payout).
Say it like a pro

"TOTP minimum, passkeys preferred, hashed recovery codes, and step-up auth for sensitive actions."

Ama role: editor post:read post:write user:delete ✘ Check at three levels 1 · Function may this role call this endpoint? (RBAC) 2 · Object is this record theirs / their org's? (ownership) 3 · Field may they see or set this column? (no mass assignment) Rules of thumb deny by default · check on the server, every request use unguessable IDs and still check ownership · centralize policy code #1 web vulnerability: Broken Access Control (IDOR)
PLATE 6 — Being logged in is not being allowed.
Chapter 6 · Authorization

Deny by default, check every object

// middleware: function-level (RBAC)
const can = (perm) => (req, res, next) =>
  (ROLE_PERMS[req.user.role] ?? []).includes(perm) ? next() : res.sendStatus(403);
router.delete('/users/:id', requireAuth, can('user:delete'), handler);

// object-level: scope the QUERY, so other people's rows simply don't exist
router.get('/orders/:id', requireAuth, async (req, res) => {
  const { rows } = await db.query(
    'SELECT * FROM orders WHERE id = $1 AND user_id = $2', [req.params.id, req.user.id]);
  if (!rows[0]) return res.sendStatus(404);        // 404, not 403: don't confirm it exists
  res.json(rows[0]);
});

// field-level: allowlist what a client may set (stops mass assignment)
const { name, bio } = req.body;                    // never: Object.assign(user, req.body)
await db.query('UPDATE users SET name=$1, bio=$2 WHERE id=$3', [name, bio, req.user.id]);
IDOR
changing /orders/41 to /orders/42 and seeing someone else's data
ABAC / ReBAC
rules over attributes or relationships ("editors of this doc"); tools: OPA, Cedar, OpenFGA
privilege
role/claims come from your database, never from the request body
Say it like a pro

"Role check at the route, ownership in the query, field allowlists, and 404 on someone else's object."

XSSattacker's script runs in your page→ encode output · CSP CSRFanother site makes your browser act→ SameSite · CSRF token SQL injectioninput becomes query code→ parameterized queries Clickjackingyour site hidden in an iframe→ frame-ancestors 'none' Also on the list SSRF: server tricked into calling internal URLs → allowlist outbound hosts open redirect: ?next= pointing offsite → validate against known paths brute force / credential stuffing → rate limits, MFA, breached-password checks unsafe file upload → type/size limits, random names, store outside web root
PLATE 7 — Most attacks have one dependable defence each. Apply them everywhere.
Chapter 7 · Common web attacks

The defences that belong in every app

// npm i helmet cors express-rate-limit csurf-alternative (or double-submit token)
const helmet = require('helmet');
app.use(helmet({
  contentSecurityPolicy: { directives: {
    defaultSrc: ["'self'"], scriptSrc: ["'self'"],            // no inline scripts
    frameAncestors: ["'none'"], objectSrc: ["'none'"], baseUri: ["'self'"],
  }},
}));
app.use(require('cors')({ origin: ['https://app.example.com'], credentials: true }));   // never '*' with credentials
app.use('/auth', require('express-rate-limit')({ windowMs: 15*60*1000, limit: 10 }));

// XSS: render user text as text
element.textContent = comment;               // not innerHTML
// React escapes by default; avoid dangerouslySetInnerHTML (sanitize with DOMPurify if you must)

// SQLi: always parameters
db.query('SELECT * FROM users WHERE email = $1', [email]);

// CSRF: SameSite=Lax cookies + a per-session token on state-changing requests
// (or send tokens in an Authorization header, which cross-site forms can't set)
CORS
relaxes the browser's rules; it is not a defence, so don't treat it as access control
CSP
the safety net if you miss an XSS hole
test your own
OWASP ZAP and Burp against a staging copy you own
Say it like a pro

"Encode output, parameterize queries, SameSite plus CSRF tokens, a tight CSP, and rate limits on auth routes."

Vault / KMS env at runtime App ✘ never: git repo · Docker image layers · client-side bundle · logs TLS 1.2+TLS / mTLS Secrets hygiene rotate on a schedule and instantly after any exposure scan commits for them · separate keys per environment · least privilege
PLATE 8 — A secret in git is a secret on the internet. Keep keys out of code and encrypt the wire.
Chapter 8 · Secrets, TLS & headers

Keep keys out of code and traffic out of sight

$ echo ".env" >> .gitignore ; git rm --cached .env
$ gitleaks detect                       # find secrets already committed
$ gitleaks protect --staged              # run as a pre-commit hook
$ openssl rand -base64 48                 # generate keys properly
$ sudo certbot --nginx -d example.com     # free TLS certificate, auto-renew
$ curl -sI https://example.com | grep -iE 'strict-transport|content-security|x-content-type|referrer'
# nginx: HTTPS + security headers
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
ssl_protocols TLSv1.2 TLSv1.3;
  • Leaked a key? Revoke and rotate first. Deleting the commit doesn't un-leak it.
  • Encrypt sensitive columns (tokens, PII) with a key held outside the database.
  • Keep dependencies patched: npm audit, Dependabot, lockfiles.
Say it like a pro

"Secrets from a vault at runtime, TLS everywhere with HSTS, and a leaked key means rotate immediately."

Log every auth event login ok / failed · logout MFA enrol / disable · reset role or permission change access denied (403) spikes who · what · when · IP · result Alert on 50 failures for one account many accounts from one IP login from a new country admin created at 3 a.m. Launch checklist ☐ argon2id/bcrypt · breach check · rate limits ☐ HttpOnly+Secure+SameSite cookies · session regenerated on login ☐ MFA available (required for admins) · tested recovery path ☐ authZ on every route and object · CSP + HSTS + CORS allowlist ☐ secrets in a vault · logs without secrets · alerts wired up
PLATE 9 — Assume something will get through. Make sure you notice.
Chapter 9 · Monitoring & review

Log it, alert on it, test it

// an audit log helper (never log passwords, tokens, or full card numbers)
function audit(req, event, extra = {}) {
  req.log.info({ audit: true, event, userId: req.user?.id, ip: req.ip,
                 ua: req.headers['user-agent'], ...extra });
}
audit(req, 'login.failed', { email: hashEmail(req.body.email) });
audit(req, 'role.changed', { target: id, from: 'user', to: 'admin' });
  1. Threat-model first: who would attack this, what do they want, and where's the weakest door?
  2. Test your own app: a staging copy with OWASP ZAP, plus a manual check that user A can't read user B's data.
  3. Automate: dependency and secret scanning in CI; fail the build on high-severity findings.
  4. Rehearse: know how to revoke all sessions, rotate keys, and lock an account in minutes.
reference
OWASP ASVS, Cheat Sheet Series (Authentication, Session, CSRF), and NIST SP 800-63B
next steps
add WebAuthn, then step-up auth, device trust, and anomaly detection
Say it like a pro

"We log every auth event, alert on anomalies, test authorization with two users, and can revoke everything on demand."