Lesson 7 of 8 · 14 min · Authentication
Sessions versus JWT, and password hashing
What you will learn
- The difference between authentication and authorisation
- How server sessions and JWTs work, and when to choose each
- Cookie settings that keep a session secure
- Store passwords correctly with bcrypt, Argon2 or scrypt
- Build register and login endpoints and defend against brute force
In simple words
Authentication answers "who are you?". HTTP has no memory: every request is separate, so after a user logs in, the server needs a way to recognise them on the next request. There are two classic ways. A session is like a cloakroom ticket: the server remembers who you are and gives you a number to show. A JWT is like a signed ID badge: it contains your details and a signature, so the server can trust it without looking anything up. Passwords themselves must never be stored as they are; they are turned into a scrambled fingerprint that cannot be reversed.
Words to know
- Session: server-side memory of a logged-in user, found through a session id.
- JWT: JSON Web Token, a signed token carrying claims such as the user id and expiry.
- Hashing: a one-way scramble of data; a password hash cannot be turned back into the password.
- Salt: random data mixed into each password hash so identical passwords get different hashes.
Sessions
- The user sends their email and password to
/login. - The server checks them, creates a session record (user id, created time) in a store, and sends back a session id in a cookie.
- On later requests the browser sends the cookie automatically; the server looks up the session and knows who it is.
- Logout deletes the session on the server, which ends it immediately.
import session from "express-session";
import { RedisStore } from "connect-redis";
import { createClient } from "redis";
const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();
app.set("trust proxy", 1); // behind a load balancer: needed for secure cookies
app.use(session({
store: new RedisStore({ client: redis }), // never use the default MemoryStore in production
secret: process.env.SESSION_SECRET, // a long random value from the environment
name: "__Host-sid",
resave: false,
saveUninitialized: false,
rolling: true,
cookie: { httpOnly: true, secure: true, sameSite: "lax", maxAge: 1000 * 60 * 60 * 8 },
}));
app.post("/api/auth/login", async (req, res) => {
const user = await verifyCredentials(req.body.email, req.body.password);
if (!user) return res.status(401).json({ title: "Unauthorized", detail: "Email or password is incorrect." });
req.session.regenerate((err) => { // new id after login: prevents session fixation
if (err) throw err;
req.session.userId = user.id;
res.json({ id: user.id, name: user.name });
});
});
app.post("/api/auth/logout", (req, res) => {
req.session.destroy(() => { res.clearCookie("__Host-sid"); res.status(204).end(); });
});
Strengths: easy to revoke (delete the session), small cookie, secrets stay on the server, mature. Costs: the server needs a shared store (Redis, a database) when you run several instances, a lookup on each request, and cookies mean you need CSRF protection and care with cross-site use.
Cookie attributes (browser storage lesson): HttpOnly (JavaScript cannot read it), Secure (HTTPS only), SameSite=Lax or Strict, a sensible maxAge, and the __Host- prefix. Regenerate the id on login, set an idle and an absolute timeout, and destroy on logout.
JSON Web Tokens
A JWT is three Base64URL parts, header.payload.signature. The payload holds claims: sub (the user id), iat (issued at), exp (expiry), iss, aud, and custom ones like role. The server signs it with a secret (HS256) or a private key (RS256, ES256, EdDSA). Later it verifies the signature and expiry without a database lookup. Standard: RFC 7519; see also the JWT best-current-practice RFC 8725.
import { SignJWT, jwtVerify } from "jose"; // jose: a modern, maintained JWT library
const secret = new TextEncoder().encode(process.env.JWT_SECRET); // 32+ random bytes
export async function signAccessToken(user) {
return new SignJWT({ role: user.role })
.setProtectedHeader({ alg: "HS256" })
.setSubject(String(user.id))
.setIssuer("shop-api")
.setAudience("shop-web")
.setIssuedAt()
.setExpirationTime("15m") // short-lived
.sign(secret);
}
export async function verifyAccessToken(token) {
const { payload } = await jwtVerify(token, secret, {
issuer: "shop-api", audience: "shop-web", algorithms: ["HS256"], // pin the algorithm
});
return payload;
}
export async function requireAuth(req, res, next) {
const header = req.get("Authorization") ?? "";
const [scheme, token] = header.split(" ");
if (scheme !== "Bearer" || !token) return res.status(401).json({ title: "Unauthorized" });
try {
const claims = await verifyAccessToken(token);
req.user = { id: Number(claims.sub), role: claims.role };
next();
} catch {
res.status(401).json({ title: "Unauthorized", detail: "Invalid or expired token." });
}
}
Strengths: stateless (no store), scales across servers and services, works well for mobile apps and APIs used by many clients, and can carry identity between services. Costs and dangers:
- Revocation is hard: a valid token works until it expires. Use short lifetimes (5 to 15 minutes) with a refresh token (stored server-side so it can be revoked, rotated on use, sent in an
HttpOnlycookie), or keep a deny list for emergencies. - The payload is readable by anyone (it is only encoded). Do not put secrets or sensitive personal data in it.
- Size: tokens are larger than session ids and are sent with every request.
- Storage in the browser:
localStorageis readable by any injected script (XSS); anHttpOnlycookie avoids that but needs CSRF defences. Neither is perfect (the browser storage lesson). - Implementation mistakes are common and serious: accepting
alg: none, mixing up algorithms, weak or hard-coded secrets, not checkingexp,issandaud. Use a vetted library with explicit algorithms, and never write your own crypto. - Claims such as
rolego stale until the token expires; check critical permissions against the database.
Which one?
| Situation | Choice |
|---|---|
| A traditional web app with a browser front end on the same site | server sessions with secure cookies (simple, revocable, safest default) |
| A mobile app or many clients calling an API | short-lived JWT access tokens plus refresh tokens |
| Several microservices need to trust a login | JWTs issued by one identity provider and verified by each service |
| You need instant logout, "log out everywhere", or admin kill-switches | sessions (or opaque tokens looked up server-side) |
| Single sign-on with Google or a company directory | OpenID Connect (next lesson), where the identity provider issues tokens |
"JWT versus sessions" is not a contest of modern against old: opaque session ids plus a server-side lookup are often the better and simpler answer; JWTs shine when statelessness across services is a real requirement. Whichever you use, buy rather than build where possible: an identity provider (Keycloak, Auth0, Clerk, AWS Cognito, Firebase Auth, Supabase Auth) handles passwords, MFA, recovery and attacks for you.
Password hashing
Never store passwords in plain text or with a fast hash (MD5, SHA-1, SHA-256): attackers who steal the database can test billions of guesses a second. Use a deliberately slow, salted, adaptive algorithm (OWASP's order of preference: Argon2id, then scrypt, then bcrypt, then PBKDF2):
// Argon2id with the "argon2" package (a native module)
import argon2 from "argon2";
const hash = await argon2.hash(password, { type: argon2.argon2id }); // includes a random salt and parameters
const ok = await argon2.verify(hash, attempt); // constant-time comparison
// bcrypt (very common; cost factor 12 or higher; note the 72-byte input limit)
import bcrypt from "bcrypt";
const h = await bcrypt.hash(password, 12);
const same = await bcrypt.compare(attempt, h);
// scrypt is built into Node.js (no dependency)
import { scrypt, randomBytes, timingSafeEqual } from "node:crypto";
import { promisify } from "node:util";
const scryptAsync = promisify(scrypt);
export async function hashPassword(password) {
const salt = randomBytes(16);
const key = await scryptAsync(password, salt, 64);
return `${salt.toString("hex")}:${key.toString("hex")}`;
}
export async function verifyPassword(password, stored) {
const [saltHex, keyHex] = stored.split(":");
const key = await scryptAsync(password, Buffer.from(saltHex, "hex"), 64);
return timingSafeEqual(key, Buffer.from(keyHex, "hex")); // constant time
}
Key points:
- The stored value contains the algorithm, parameters, salt and hash in one string, so you can verify later and upgrade parameters over time (rehash at next login if the cost is outdated).
- A salt is unique per password, so identical passwords produce different hashes and precomputed (rainbow table) attacks fail. Libraries add it automatically.
- Use the asynchronous versions: hashing is deliberately CPU-heavy; synchronous calls block the event loop (the runtime lesson). Under load, limit concurrent hashing or use a worker pool.
- Compare with constant-time functions (
timingSafeEqual, or the library'sverify/compare). - Optionally add a pepper (a secret key kept outside the database, in a secret manager) for defence in depth.
- Password policy (NIST guidance): require a minimum length (8 characters or more, ideally allow 64), allow all characters and spaces and paste, check against breached passwords (Have I Been Pwned's k-anonymity API), do not force periodic changes or composition rules, and support MFA.
Register and login endpoints
router.post("/register", validate(registerSchema), async (req, res) => {
const { email, password, name } = req.validBody;
const existing = await users.findByEmail(email.toLowerCase());
if (existing) throw new ConflictError("An account with this email already exists.");
const user = await users.create({ email: email.toLowerCase(), name, passwordHash: await hashPassword(password) });
res.status(201).json({ id: user.id, email: user.email, name: user.name }); // never return the hash
});
router.post("/login", loginLimiter, validate(loginSchema), async (req, res) => {
const { email, password } = req.validBody;
const user = await users.findByEmail(email.toLowerCase());
const ok = user ? await verifyPassword(password, user.passwordHash) : await verifyPassword(password, DUMMY_HASH); // same work either way
if (!ok) return res.status(401).json({ title: "Unauthorized", detail: "Email or password is incorrect." });
// ... create session or tokens
});
- Same message for "unknown email" and "wrong password" (avoid account enumeration), and do equal work (verify against a dummy hash) so response time does not reveal whether the email exists. Registration and password-reset flows should also avoid revealing which emails exist where possible.
- Rely on a database unique index on the email to prevent duplicate registrations (a race otherwise).
- Verify emails with a signed, expiring link or code before trusting them; send password-reset links with single-use, short-lived, random tokens (store a hash of the token), and invalidate sessions after a password change.
Brute-force and abuse protection
import rateLimit from "express-rate-limit";
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
limit: 10, // 10 attempts per 15 minutes per IP
standardHeaders: true,
legacyHeaders: false,
});
Also: lock or slow down per account after repeated failures (with care, to avoid denial of service against a victim), add CAPTCHA on suspicious activity, use MFA (TOTP apps, WebAuthn passkeys, SMS only as a last resort), monitor and alert on credential-stuffing patterns, and log authentication events (without logging passwords or tokens). Serve everything over HTTPS and set Strict-Transport-Security.
Common mistakes
- Plain-text, MD5 or SHA-256 passwords.
- Different error messages for unknown user and wrong password.
- JWTs with long lifetimes, weak secrets or unverified
alg,exp,iss,aud. - Putting secrets or roles that must be exact in a JWT payload.
- Using the in-memory session store in production, or not regenerating the session id at login.
- Synchronous hashing in request handlers.
- No rate limiting on login.
- Returning the password hash in API responses.
Try it yourself
- Implement register and login with scrypt or Argon2 and a unique email index; test that two users with the same password have different hashes.
- Add
express-sessionwith Redis, secure cookie settings,regenerateon login anddestroyon logout. - Implement JWT access tokens with
jose(15 minutes), arequireAuthmiddleware, and test expired and tampered tokens. - Add a login rate limiter and test the 429 response.
- Time the login endpoint for unknown and known emails to confirm similar response times.
Check yourself
What is the main difference between sessions and JWTs?
A session keeps user state on the server and gives the client an opaque id; a JWT carries signed claims in the token itself so the server can verify it without a lookup, at the cost of harder revocation.
Why must passwords be hashed with bcrypt, scrypt or Argon2 and not SHA-256?
They are deliberately slow and salted, making large-scale guessing after a database leak impractical; fast hashes can be tested billions of times per second.
Why use the same error message for "unknown email" and "wrong password"?
Different messages let attackers discover which emails have accounts (account enumeration).
Is the payload of a JWT secret?
No. It is only Base64-encoded and readable by anyone holding the token; the signature protects integrity, not confidentiality.
Interview questions
How would you implement authentication for a Node.js API?
Hash passwords with Argon2id or bcrypt, validate input, and issue either server sessions (secure HttpOnly cookies, Redis store) or short-lived JWT access tokens with rotating refresh tokens; add rate limiting, HTTPS, CSRF protection for cookies, MFA options and consistent error messages; or delegate to an identity provider.
How do you revoke a JWT?
Since it is stateless, keep access tokens short-lived, store refresh tokens server-side so they can be revoked and rotated, and use a deny list or token version in the user record for emergency invalidation.
What is a salt, and what is a pepper?
A salt is a unique random value stored with each password hash to defeat precomputed attacks; a pepper is a secret value kept outside the database, mixed into hashing as an additional layer.
Summary
- Sessions keep state on the server behind an opaque, secure cookie; JWTs are signed, stateless tokens that need short lifetimes and careful verification.
- Choose sessions for browser apps by default, JWTs for multi-client or multi-service setups, or use an identity provider.
- Store passwords with Argon2id, scrypt or bcrypt, asynchronously, with constant-time comparison and a modern password policy.
- Protect login with generic errors, rate limits, MFA and HTTPS.
Going deeper
- OWASP: Password Storage Cheat Sheet: current algorithm and parameter guidance.
- OWASP: Session Management Cheat Sheet: secure sessions and cookies.
- RFC 7519: JSON Web Token: the JWT standard.
- Node.js: crypto.scrypt and timingSafeEqual: built-in hashing primitives.
See how much of this you can explain
A free mock interview asks you new questions on Node.js and Express backends for Full Stack Developer and scores every answer, with what to fix.