Authentication Flaws
Weak passwords, brute force, credential stuffing, and how to implement authentication that actually holds up
Skills taught: websecurity.auth-flaws, websecurity.rate-limiting, websecurity.mfa, websecurity.password-hashing, websecurity.account-enumeration
Common authentication failures
WEAK PASSWORD POLICIES:
Allowing 'password123', '123456', common words
No minimum length (8+ chars; 12+ recommended)
No check against breached password lists
Fix: validate against Have I Been Pwned API, enforce complexity
BRUTE FORCE / CREDENTIAL STUFFING:
No rate limiting on login endpoint
Attackers try millions of username/password pairs from leaked databases
Fix: rate limit by IP + username, lockout after N failures, CAPTCHA
ACCOUNT ENUMERATION:
Login returns 'User not found' vs 'Wrong password' — reveals valid usernames
Password reset returns 'Email not registered' — reveals account existence
Fix: return identical messages regardless of which check failed
INSECURE PASSWORD STORAGE:
Storing passwords in plaintext or with MD5/SHA1 (reversible with rainbow tables)
Fix: use bcrypt, scrypt, or Argon2id — never MD5/SHA1/SHA256 for passwords
MISSING SECURE FLAGS ON SESSION TOKENS:
Session cookies without HttpOnly/Secure/SameSite
Session IDs in URLs (?sessionId=abc) — logged by proxies, shared in URLs
Fix: HttpOnly + Secure + SameSite=Lax cookies, never expose session in URL
NO MFA FOR HIGH-VALUE ACTIONS:
No second factor for password changes, payment additions, privilege escalation
Fix: require MFA for account changes and sensitive operations
Password hashing with bcrypt
import bcrypt from 'bcrypt'; // npm install bcrypt
// WHY bcrypt (not SHA256/MD5):
// 1. Slow by design — cost factor makes brute force expensive
// 2. Built-in salt — prevents rainbow table attacks
// 3. Adaptive — increase cost as hardware gets faster
const SALT_ROUNDS = 12; // 2^12 = 4096 iterations; adjust up as hardware improves
// Rule of thumb: should take ~300ms on your server
// 10 = 100ms, 12 = 400ms, 14 = 1.5s — higher is safer but slower on login
// Registration
async function registerUser(email: string, password: string) {
// Check against breached passwords before hashing
const isPwned = await checkHaveIBeenPwned(password);
if (isPwned) {
throw new Error('This password appeared in a data breach. Choose a different one.');
}
const hash = await bcrypt.hash(password, SALT_ROUNDS);
// hash looks like: $2b$12$... (includes algorithm, cost, salt, and hash)
await db.users.create({ email, passwordHash: hash });
}
// Login — constant-time comparison (bcrypt.compare is already constant-time)
async function loginUser(email: string, password: string) {
const user = await db.users.findByEmail(email);
// CRITICAL: Always run bcrypt.compare even if user not found
// Otherwise, 'email not found' returns faster than 'wrong password'
// — a timing side-channel that reveals valid email addresses
const dummyHash = '$2b$12$invalidhashfortimingnormalization...';
const hash = user?.passwordHash ?? dummyHash;
const valid = await bcrypt.compare(password, hash);
// Return identical error regardless of whether email or password was wrong
if (!user || !valid) {
throw new Error('Invalid email or password');
// NOT: 'Email not found' or 'Wrong password' — those reveal too much
}
return user;
}
Rate limiting and account lockout
import rateLimit from 'express-rate-limit'; // npm install express-rate-limit
import RedisStore from 'rate-limit-redis'; // npm install rate-limit-redis
// IP-based rate limit for login — prevents brute force
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 10, // 10 attempts per IP per window
message: { error: 'Too many login attempts. Try again in 15 minutes.' },
standardHeaders: true, // Return RateLimit-* headers
legacyHeaders: false,
// In production: use Redis to share limits across multiple servers
// store: new RedisStore({ client: redisClient }),
});
// Apply only to login endpoint
app.post('/api/auth/login', loginLimiter, loginHandler);
// Progressive account lockout (more sophisticated)
async function loginHandler(req, res) {
const { email, password } = req.body;
// Check if account is temporarily locked
const failCount = await redis.get(`login_fails:${email}`) || 0;
if (failCount >= 5) {
const ttl = await redis.ttl(`login_fails:${email}`);
return res.status(429).json({
error: `Account temporarily locked. Try again in ${Math.ceil(ttl / 60)} minutes.`
});
}
try {
const user = await loginUser(email, password);
await redis.del(`login_fails:${email}`); // Reset on success
// ... issue session
} catch {
// Increment failure counter with 30-minute expiry
await redis.incr(`login_fails:${email}`);
await redis.expire(`login_fails:${email}`, 30 * 60);
res.status(401).json({ error: 'Invalid email or password' });
}
}
Frequently Asked Questions
Should I implement my own authentication or use a library?
Use a battle-tested library or service (Passport.js, Auth.js/NextAuth, Clerk, Auth0, Supabase Auth) unless you have a compelling reason to build from scratch. Authentication has many subtle failure modes — timing attacks, session fixation, concurrent login handling, secure token generation — that libraries have already solved. If you do build it yourself, have a security expert review it. The cost of a breach far exceeds the time saved by rolling your own auth.