Authentication & Password Security
Authentication vs authorisation
- Authentication: who are you? (log in)
- Authorisation: what are you allowed to do? (permissions, roles, RLS)
How logins stay logged in
| Approach | How it works | Notes |
|---|---|---|
| Session cookie | the server stores the session; the browser holds a session ID in an HttpOnly cookie | easy to revoke; needs a session store |
| JWT | a signed token holds the user's id and expiry; sent as Authorization: Bearer … | stateless and scalable; hard to revoke early, so keep expiry short |
| OAuth / social login | "Sign in with Google or GitHub" | no passwords to store; use a library or provider |
Passwords: never store them in plain text
- Hash with a slow, salted algorithm: bcrypt, argon2 or scrypt. Never MD5 or SHA-256 alone.
- Compare with the library's
comparefunction. - Rate-limit login attempts and lock accounts after repeated failures.
- Offer password reset by email with single-use, expiring links.
Easiest safe option
Use a provider: Supabase Auth, Firebase Auth, Auth0 or Clerk. They handle hashing, email verification, OAuth and token refresh for you.
Cookie flags for login sessions
HttpOnly (JavaScript can't read it), Secure (HTTPS only), SameSite=Lax or Strict (helps block CSRF).
Example
import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";
const users = []; // demo only — use a database
export async function register(email, password) {
if (password.length < 8) throw new Error("Password must be 8+ characters");
const hash = await bcrypt.hash(password, 12); // salted, slow on purpose
users.push({ id: users.length + 1, email, hash });
}
export async function login(email, password) {
const user = users.find((u) => u.email === email);
const ok = user && (await bcrypt.compare(password, user.hash));
if (!ok) throw new Error("Invalid email or password"); // don't reveal which one
return jwt.sign({ sub: user.id }, process.env.JWT_SECRET, { expiresIn: "15m" });
}
export function requireAuth(req, res, next) {
const token = req.get("authorization")?.replace("Bearer ", "");
try {
req.user = jwt.verify(token, process.env.JWT_SECRET);
next();
} catch {
res.status(401).json({ error: "Please log in" });
}
}
// 💻 npm install bcrypt jsonwebtoken — run in a Node/Express project