Nine spreads on how logins, sessions, tokens, OAuth and permissions work, and the attacks that target them, with Node.js examples you can adapt.
"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.
// 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 */ }
"Argon2id with a per-user salt, constant-time verify, identical error messages, and breach-checked passphrases."
// 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));
"HttpOnly, Secure, SameSite cookies, regenerate on login, and server-side revocation."
// 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
kid)"Pinned algorithm, validated iss, aud and exp, ten-minute lifetime, and rotating refresh tokens."
client_id, redirect_uri, scope, a random state, and a PKCE code_challenge.code.code_verifier for tokens, over TLS.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',
}));
});
"Authorization code flow with PKCE, exact redirect URIs, state and nonce checked, minimal scopes."
// 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
"TOTP minimum, passkeys preferred, hashed recovery codes, and step-up auth for sensitive actions."
// 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]);
/orders/41 to /orders/42 and seeing someone else's data"Role check at the route, ownership in the query, field allowlists, and 404 on someone else's object."
// 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)
"Encode output, parameterize queries, SameSite plus CSRF tokens, a tight CSP, and rate limits on auth routes."
$ 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;
npm audit, Dependabot, lockfiles."Secrets from a vault at runtime, TLS everywhere with HSTS, and a leaked key means rotate immediately."
// 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' });
"We log every auth event, alert on anomalies, test authorization with two users, and can revoke everything on demand."