Authentication and sessions for APIs
Build a Node HTTP API from scratch, model data in SQL and MongoDB, and reason about transactions, indexes, caching and authentication so the endpoint you ship stays correct under load.
What you will be able to do
#- Hash passwords with a slow, salted algorithm.
- Compare session cookies and signed tokens.
- Set cookie flags that resist theft and CSRF.
Overview
#Authentication proves who the caller is. Store passwords only as slow hashes, and carry proof of login either in a server session referenced by a cookie or in a signed token.
Password hashing
Use bcrypt, scrypt or argon2 with a per-password salt and a cost that takes a deliberate fraction of a second. Never store or log the plaintext.
const bcrypt = require('bcrypt');
const hash = await bcrypt.hash(password, 12);
const ok = await bcrypt.compare(candidate, hash);
Sessions versus tokens
A session stores state on the server and gives the client an opaque cookie id; revoking is immediate. A JWT is self-contained and stateless, so in its pure form it cannot be revoked before it expires; keep its lifetime short and pair it with a refresh token. Adding a server-side denylist allows revocation at the cost of reintroducing shared state.
Cookie flags
HttpOnlyblocks JavaScript access, limiting XSS token theft.Securesends the cookie only over HTTPS.SameSite=LaxorStrictmitigates CSRF.PathandMax-Agebound scope and lifetime.
Common pitfalls
- Hashing with fast algorithms like MD5 or SHA-256, which are cheap to brute force.
- Storing a JWT in localStorage where XSS can read it.
- Omitting SameSite and shipping a CSRF-able cookie.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Debug
This code stores passwords in a way that is trivially reversible. Fix it.
starter.javascriptconst hash = crypto.createHash('sha256').update(password).digest('hex'); await db.query('INSERT INTO users (email, password) VALUES ($1, $2)', [email, hash]);Reveal the reference answer
reference.javascriptconst bcrypt = require('bcrypt'); const hash = await bcrypt.hash(password, 12); await db.query('INSERT INTO users (email, password_hash) VALUES ($1, $2)', [email, hash]);Authored expected output: Passwords stored as a slow bcrypt hash with a per-password salt.
SHA-256 is fast, so an attacker can test billions of guesses per second. bcrypt with a cost factor is deliberately slow and salts each hash.
Exercise 2Predict
A session cookie is set without HttpOnly. What class of attack can now read it?
Read the code, then choose the best answer. The reference explanation stays hidden until you respond. stimulus.txtSet-Cookie: sid=abc123; Secure; SameSite=Lax
Common misconceptions
#- Encrypting passwords is enough: hashing is required, because encryption is reversible.
- JWTs are more secure than sessions: both are sound; JWTs trade revocability for statelessness.
Follow-up practice
#- backend-databases-authorization
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.