Authentication (who are you?)

Authentication checks a user's identity. If it is weak, attackers log in as someone else.

Common attacks

  • Credential stuffing: logging in with passwords leaked from other sites
  • Brute force: guessing passwords over and over
  • Plain-text or weakly hashed passwords: after a database leak, attackers read every password
  • User enumeration: an error like "email not found" tells attackers which accounts exist

Packages

PackageUse
argon2 / bcryptPassword hashing (slow on purpose, salted)
passportAuth strategies (local, Google, GitHub…)
otplibTOTP codes for MFA (Google Authenticator)
qrcodeQR code for MFA setup
zxcvbnPassword strength check

❌ Vulnerable

// Plain text password + user enumeration
const user = await User.findOne({ email });
if (!user) return res.status(404).json({ error: 'Email not found' });
if (user.password !== password) return res.status(401).json({ error: 'Wrong password' });

✅ Secure

const argon2 = require('argon2');

// Signup
const hash = await argon2.hash(password); // salt is built in
await User.create({ email, passwordHash: hash });

// Login
const user = await User.findOne({ email });
const ok = user && await argon2.verify(user.passwordHash, password);
if (!ok) return res.status(401).json({ error: 'Invalid email or password' }); // same message for both cases

MFA (TOTP)

const { authenticator } = require('otplib');
const secret = authenticator.generateSecret();          // store per user (encrypted)
const otpauth = authenticator.keyuri(email, 'MyApp', secret); // turn into a QR code
const valid = authenticator.verify({ token: req.body.code, secret });

Checklist

  • Hash passwords with argon2id or bcrypt (cost ≥ 12); never MD5 or SHA-1
  • Same error message for "wrong email" and "wrong password"
  • Rate limit and lock out after failed logins (see 08-rate-limiting)
  • MFA for admins, and offer it to users
  • Minimum password length of 8 or more; check against breached-password lists
  • Reset tokens: random, single use, expire within 15–30 min
  • Re-ask for the password before sensitive actions (change email, delete account)