KelasSource ↗
← All lessons

How JWT login works

headerpayloadsignature

Log in and use the token

Browsertoken saved
Server
Databaseskipped

browser.js

const res = await fetch("/login", {  method: "POST",  body: JSON.stringify({ email, password }),});const { token } = await res.json();localStorage.setItem("token", token); const me = await fetch("/me", {  headers: { Authorization: `Bearer ${token}` },});const user = await me.json();

server.js

app.post("/login", async (req, res) => {  const user = await db.findUser(req.body.email);  const ok = await bcrypt.compare(req.body.password, user.hash);  if (!ok) return res.status(401).end();  const token = jwt.sign({ sub: user.id, email: user.email }, SECRET, { expiresIn: "15m" });  res.json({ token });}); app.get("/me", (req, res) => {  const token = req.headers.authorization.split(" ")[1];  const claims = jwt.verify(token, SECRET);  res.json(claims);});
02

Passwords are stored as bcrypt hashes never as text

signup.js

const salt = await bcrypt.genSalt(10);const hash = await bcrypt.hash(password, salt);await db.insert({ email, hash });

login.js

const user = await db.findUser(email);const ok = await bcrypt.compare(attempt, user.hash); // what compare() does insideconst salt = user.hash.slice(0, 29);const again = await bcrypt.hash(attempt, salt);return again === user.hash;
03

Inside the token is just readable JSON

NameRoleuseradmin
Token

Header
Payload
Signature

Anyone can read the payload. Never put a password in it

sign.js

const header = base64url(JSON.stringify({ alg: "HS256", typ: "JWT" }));const payload = base64url(JSON.stringify({ sub: "42", name, role }));const signature = hmacSha256(`${header}.${payload}`, SECRET);const token = `${header}.${payload}.${signature}`;
04

Try to cheat and the signature catches it

You
Server

verify.js

function verify(token) {  const [header, payload, signature] = token.split(".");  const expected = hmacSha256(`${header}.${payload}`, SECRET);  if (signature !== expected) {    throw new Error("invalid signature");  }  return JSON.parse(base64url.decode(payload));}
05

Tokens expire so a stolen one dies fast

Time since login0 min
Payload

server.js

const claims = verify(token);if (Date.now() / 1000 > claims.exp) {  return res.status(401).json({ error: "jwt expired" });}res.json(claims);

browser.js

if (res.status === 401) {  // the refresh token lives in an httpOnly cookie  const r = await fetch("/refresh", { method: "POST", credentials: "include" });  const { token } = await r.json();  localStorage.setItem("token", token);}

That's the newest lesson

All lessons