Belajar
← All lessons

How cookies and sessions work

Log in and get a session cookie

Browser
shop.test
Sessions

browser.js

await fetch("/login", {  method: "POST",  body: JSON.stringify({ email, password }),});// nothing here saves the cookie. The browser does const res = await fetch("/account");// the browser adds the Cookie header by itselfconst page = await res.json();

server.js

app.post("/login", async (req, res) => {  const user = await db.checkLogin(req.body);  const sid = crypto.randomBytes(18).toString("base64url");  await sessions.set(sid, { userId: user.id });  res.cookie("sid", sid, { httpOnly: true, secure: true });  res.json({ ok: true });}); app.get("/account", async (req, res) => {  const session = await sessions.get(req.cookies.sid);  if (!session) return res.status(401).end();  res.json(await db.user(session.userId));});

Attributes decide where it goes and who can read it

HttpOnlySecureSameSiteStrictLaxNonePath//accountDomainNot setshop.testMax-AgeNot set36000
Response header

server.js

res.cookie("sid", sid, {  httpOnly: true,       // no document.cookie  secure: true,         // HTTPS only  sameSite: "lax",      // cross-site rules  path: "/",  domain: "shop.test",  // and its subdomains  maxAge: 3600 * 1000,  // 1 hour});

browser (inside)

function attach(cookie, req) {  if (cookie.secure && req.scheme !== "https") return false;  if (!hostMatches(req.host, cookie.domain)) return false;  if (!req.path.startsWith(cookie.path)) return false;  if (req.crossSite) {    if (cookie.sameSite === "strict") return false;    if (cookie.sameSite === "lax") return req.isLinkClick;  }  return true;}

Logging out has to happen on the server

You
shop.test
Attacker

logout.js

app.post("/logout", async (req, res) => {  await sessions.delete(req.cookies.sid);  res.clearCookie("sid");  res.status(204).end();});

server.js

app.use(async (req, res, next) => {  const session = await sessions.get(req.cookies.sid);  if (!session) return res.status(401).end();  req.userId = session.userId;  next();});

Topics

Next: How OAuth login works

Open lesson