At a concert gate, you show your ID card and ticket, and the staff put a wristband on you. After that you don't need your ID again. The staff at each area just check that the wristband is genuine and not expired. The VIP area checks one more thing: the kind of wristband.
A server works the same way. The email and password you send to log in are the ID card and ticket. The wristband is a token, a proof of identity the client sends with every request after login. The staff at each area are the middleware that checks that token, and the kind of wristband is the user's role (a normal user or an admin). Proving who you are is called authentication. Deciding what you're allowed to do is called authorization. No wristband: "who are you?", that's 401. A genuine wristband but not VIP: "we know you, but you can't come in here", that's 403.
Store a password hash, not the password
A leaked database must not leak passwords. So what gets stored is the password's hash: the result of a one-way function that can't be turned back into the password. For passwords, use a hash function that is deliberately slow and uses a salt (random text per user, added to the password before hashing), such as bcrypt (npm install bcrypt). This code makes a hash of pass123, then checks two passwords against that hash. It uses await, so it must run inside an async function:
const bcrypt = require("bcrypt");
const hash = await bcrypt.hash("pass123", 10);
console.log(hash); // $2b$10$nFW9NnGRP2xZa25TT767P.S3MJI3ptEVuxVoeJI.thycUJ92dHchi
console.log(await bcrypt.compare("pass123", hash)); // true
console.log(await bcrypt.compare("pass124", hash)); // false
- The result is 60 characters:
$2b$is the algorithm,10the cost (how slow it is), the next 22 characters the salt, and the rest the hash. - If you call
bcrypt.hash("pass123", 10)twice, the results differ, because the salt is random.comparereads the salt from the stored hash. - Cost 10 means 2^10 rounds of calculation: about 70 ms on our laptop. Cost 12 is about 270 ms. You don't notice that for one login, but for an attacker trying billions of guesses it is far too slow.
SHA-256, an ordinary fast hash function, isn't suitable for passwords. pass123 always gives the same hash, and a GPU (graphics card) can compute billions of hashes per second. The modern alternative to bcrypt is Argon2id (the argon2 package). If npm install bcrypt fails on your computer, use bcryptjs. It is written in JavaScript, has the same functions (hash, compare), and its hashes match bcrypt's.
Login: match, then hand out an ID
The POST /login route below uses bcrypt to check the password, and the package jsonwebtoken to make the token (npm install jsonwebtoken). process.env.JWT_SECRET reads the secret key for tokens from an environment variable (a setting outside the code, covered in the Environment & Config lesson).
const jwt = require("jsonwebtoken");
const users = [
{ id: 1, email: "[email protected]", role: "user", passwordHash: "$2b$10$nFW9NnGRP2xZa25TT767P.S3MJI3ptEVuxVoeJI.thycUJ92dHchi" },
{ id: 2, email: "[email protected]", role: "admin", passwordHash: "$2b$10$ZMcOs6hGaflkr9wqNFSKyuH04ed0dFEu4bXjrwhmUYjSxAOD5VUW2" },
];
app.post("/login", async (req, res) => {
const { email, password } = req.body;
const user = users.find((u) => u.email === email);
const isMatch = user ? await bcrypt.compare(password, user.passwordHash) : false;
if (!isMatch) return res.status(401).json({ error: "Wrong email or password" });
const token = jwt.sign({ userId: user.id, role: user.role }, process.env.JWT_SECRET, { expiresIn: "1h" });
res.json({ token });
});
If it matches, jwt.sign makes a token holding userId and role, valid for 1 hour (expiresIn: "1h"), and res.json sends it as { token }.
An unregistered email and a wrong password get the same message ("wrong email or password"). If they differed, an attacker could check which emails have an account.
Session cookie or JWT
There are two ways to hand out the "wristband" after login: a session cookie and a JWT (explained below). A cookie is a small piece of data the browser keeps for one site. A session is a login record that the server stores.
| Session cookie | JWT | |
|---|---|---|
| What the browser holds | a random id, such as sid=7f3a... |
a token holding signed data |
| Sent through | the Cookie header, automatically by the browser |
the Authorization: Bearer <token> header |
| The server stores | a list of sessions (memory or database) | nothing, only its secret key |
| Logout | delete the session on the server, effective right away | the token stays valid until exp (its expiry time), so keep its life short |
A session cookie should carry HttpOnly (JavaScript can't read it), Secure (sent over HTTPS only) and SameSite=Lax (not sent with requests from other sites, except through a link). JWTs suit an API called by a mobile app or another server. In a web app, keep the token in an HttpOnly cookie, not in localStorage. A harmful script that gets into the page (an XSS attack) can read localStorage, but it cannot read an HttpOnly cookie.
There are three ways to build login:
| Way | When to pick it |
|---|---|
| Write it yourself with bcrypt and JWT | Learning, or a small app. This lesson uses this way so that you see every step. |
| A library: Passport or Better Auth | You need Google or GitHub login, password reset and sessions, without writing all of it yourself. |
| A service: Auth0, Clerk or Supabase Auth | You want it working fast. The service keeps the login data, and it usually costs money once you have many users. |
JWT: header, payload, signature
JWT stands for JSON Web Token: a login token written as text that carries user data and a signature from the server. This is Budi's token, made by jwt.sign with the example key an-example-secret-key-longer-than-32-characters:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEsInJvbGUiOiJ1c2VyIiwiaWF0IjoxNzkxNDI4NDAwLCJleHAiOjE3OTE0MzIwMDB9.WXuRlvIGrPNRGcy9ke5NbyrR87k4qUSZQeC5CUZVCas
Three parts separated by dots:
- Header
{"alg":"HS256","typ":"JWT"}: the signing algorithm. The header here is the first part of the token, not an HTTP header. - Payload
{"userId":1,"role":"user","iat":1791428400,"exp":1791432000}: the data.iatis when the token was made, andexpis when it expires (1 hour later). Both are written as the number of seconds since 1 January 1970. - Signature: HMAC-SHA256 of the text
header.payload, calculated with the server's secret key. HMAC is a way to calculate a fingerprint of a text with a key.
The header and payload are only base64url encoded, not encrypted. Encoding only changes how the text is written, so anyone can read it. Never put a password there. What protects the token is its signature: without the secret key, nobody can make a matching one. For example, Budi opens his token and changes role to admin. The payload changes, so the old signature no longer matches, and jwt.verify (the function that checks a token) throws JsonWebTokenError: invalid signature. The server answers 401 {"error":"Invalid token"}.
jwt.sign(payload, secret) makes a token. jwt.verify(token, secret) checks the signature and exp, then returns the payload. An expired token gives TokenExpiredError: jwt expired.
Auth middleware: 401 or 403
Two middleware functions guard the notes routes: requireLogin checks the token, requireAdmin checks for the admin role.
function requireLogin(req, res, next) {
const [scheme, token] = (req.headers.authorization || "").split(" ");
if (scheme !== "Bearer" || !token) {
return res.status(401).json({ error: "Login required" });
}
try {
req.user = jwt.verify(token, process.env.JWT_SECRET);
next();
} catch (err) {
res.status(401).json({ error: "Invalid token" });
}
}
function requireAdmin(req, res, next) {
if (req.user.role !== "admin") {
return res.status(403).json({ error: "Admins only" });
}
next();
}
app.get("/notes", requireLogin, (req, res) => res.json(notes));
app.delete("/notes/:id", requireLogin, requireAdmin, (req, res) => {
notes = notes.filter((n) => n.id !== Number(req.params.id));
res.status(204).end();
});
If jwt.verify succeeds, requireLogin stores the token's payload in req.user, so requireAdmin, which runs after it, can read req.user.role.
| Request | Answer |
|---|---|
GET /notes with no header |
401 {"error":"Login required"} |
GET /notes with Budi's token |
200, the list of notes |
DELETE /notes/2 with Budi's token |
403 {"error":"Admins only"} |
DELETE /notes/2 with Siti's token |
204, deleted |
DELETE /notes/1 with Budi's token changed to admin |
401 {"error":"Invalid token"} |
The Authorization header looks like Bearer <token>, so .split(" ") separates the word Bearer from the token. jwt.verify(req.headers.authorization, ...) without cutting it fails with JsonWebTokenError: invalid token.
In the exercise: a simple login
In the exercise, login is a plain function, with no real bcrypt or JWT, so the flow is easy to see. users holds Budi ([email protected], pass123) and Siti ([email protected], pass456). generateToken(userId) returns "token-" + userId. login(email, password) uses users.find(...) to look for the user whose email and password both match. If found, the result is { success: true, token: generateToken(user.id) }. If not, the result is { success: false, error: "Wrong email or password" }, with no token. Plain-text passwords here are only for practice. A real app stores bcrypt hashes.
⚠️ Auth that leaks or answers wrong
- Storing the real password, or a fast hash such as MD5 or SHA-256. Use bcrypt or Argon2id.
- Putting secret data in a JWT payload. Anyone holding the token can read the payload.
- Forgetting to cut off
Bearer.jwt.verifygets"Bearer eyJ..."and fails. - A short secret key, or one written in the code. Keep it in an environment variable (
JWT_SECRET), at least 32 random characters. A leaked key means anyone can make an admin token. IfJWT_SECRETis not set, login fails withError: secretOrPrivateKey must have a value. Check the required variables when the app starts (covered in the Environment & Config lesson). - A login with no limit on attempts. An attacker can try thousands of passwords per minute. Limit it with the
express-rate-limitpackage, for example 5 attempts per 15 minutes:app.post("/login", rateLimit({ windowMs: 15 * 60 * 1000, limit: 5 }), ...). The sixth attempt gets429(Too Many Requests). - Mixing up 401 and 403. 401: who you are isn't proven yet. 403: you're known, but you don't have permission.
TL;DR: Authentication proves who you are, authorization decides what you may do. Store passwords as bcrypt hashes (the result of a one-way function that can't be reversed), never the real text or a fast hash such as SHA-256. Make one with bcrypt.hash(password, 10), check it with bcrypt.compare. After login, the server hands out an ID: a session cookie (a random id in the browser; the server keeps the login record) or a JWT (JSON Web Token). A JWT has three parts: header, payload (the user data) and signature (an HMAC-SHA256 signature made with the server's secret key). jwt.sign makes the token, jwt.verify checks it. Anyone can read a JWT's payload, but changing it breaks the signature, so jwt.verify rejects it. The middleware reads the HTTP header Authorization: Bearer <token>, cuts off the word Bearer with .split(" ")[1], then answers 401 when the token is missing or invalid, and 403 when the user is known but lacks permission.
⚡ Store the hash, not the password
Write:
const hash = await bcrypt.hash("pass123", 10);
console.log(await bcrypt.compare("pass123", hash)); // true
Meaning: bcrypt.hash makes a hash of the password: the result of a one-way function that can't be reversed. bcrypt.compare checks a password against that hash, and gives true when they match. bcrypt is slow on purpose (the 10 sets how slow) and uses a salt (random text per user), so a leaked database doesn't leak the passwords.
⚡ A JWT can be read, but not forged
Guess first: Budi, a normal user, opens his JWT (login token) and changes role to admin. What happens when the server checks that token?
jwt.verify, the function that checks a token, throws JsonWebTokenError: invalid signature. The payload (the data part of the token) changed, so the old signature (the server's signature) no longer matches.
Meaning: The header (the first part of the token) and the payload are only encoded, which means written in another form, not encrypted. Anyone can read them, so never put a password there. What protects the token is the signature, which can only be made with the server's secret key.
⚡ Cut off Bearer first
Write:
const [scheme, token] = (req.headers.authorization || "").split(" ");
if (scheme !== "Bearer" || !token) {
return res.status(401).json({ error: "Login required" });
}
req.user = jwt.verify(token, process.env.JWT_SECRET);
Meaning: The HTTP header Authorization holds Bearer <token>. .split(" ") separates the word Bearer (into scheme) from the token. Without .split(" "), jwt.verify gets "Bearer eyJ..." and fails. process.env.JWT_SECRET is the server's secret key. 401: who you are isn't proven yet. 403: you're known, but you don't have permission.