15 min read
Session-based authentication: how login works
In one sentence: Signing in is checking the password once and getting in return a long, random id, which the browser sends back in a cookie. The server keeps only its hash and until when it’s valid: really signing out is deleting that row, not the cookie.
What you will learn
- Explain what happens when you sign in and on every request after that.
- Store sessions with their hash and their expiry, and really close them on the server.
- Say what each attribute of the session cookie stops.
- Prevent session fixation and stop the login from revealing which emails have an account.
Before you start, read: 01-passwords.md
The problem
Section titled “The problem”In lesson 1, “Passwords,” Marta created her account. Today she signs in: she types her email and her password once, and then makes ten more requests. How does the API know that all ten are Marta’s?
HTTP doesn’t remember anything from one request to the next (lesson 5 of Phase 2). Sending the password with each one would force the browser to keep it, and every request would pay the 20 ms of the Password hashingStoring a password as its hash, calculated with a deliberately slow algorithm and with a salt, instead of the password itself. To check it, the calculation is repeated with what the person types and the two results are compared; the password can’t be recovered from what’s stored.Go to definition.
The answer is a Session (on a website)What a server remembers about a visitor from one request to the next, such as who they are or what’s in their cart. The server keeps that data under a long, random identifier, and the browser only keeps that identifier, almost always in a cookie.Go to definition, and it brings three questions:
- What does the browser keep, and what does the server keep?
- What happens if someone copies what the browser keeps?
- When Marta clicks “Sign out” on a library computer, is she really signed out?
The analogy
Section titled “The analogy”The analogy
At the gate of a festival they ask for your ticket and your ID, just once, and put a wristband with a long code on you. At every bar they scan the code, and the festival’s computer says whether it’s valid and whose it is.
If you lose the wristband, they cancel the code at the entrance. Cutting it off isn’t enough if someone took a photo of it. And it’s valid until the last day of the festival.
Where the analogy breaks down
- Nobody takes your wristband off without you noticing. A cookie can be copied without you finding out, and the copy is worth the same as the original.
- At the bar they see your face. The server sees nobody: to it, whoever brings the id is Marta.
- The festival keeps the codes as they are; the shop, only their hash.
How it really works
Section titled “How it really works”Signing in: the password once, and an id in return
Section titled “Signing in: the password once, and an id in return”- The shop's APIargon2: does the password match?
- The shop's API → Marta's browser200 OK
Set-Cookie: session=A4vjwCNu… - The shop's API → Marta's browser200 OK
Marta's account
There are two moments: signing in, once, and every request after that. The sign-in route, in src/v2.ts:
// The same 400, with the same body, for an email that doesn't exist and for a wrong password:// whoever tries doesn't know which of the two has failed, nor whether that email has an account.v2.openapi(contract.signIn, async (c) => { const { email, password } = c.req.valid('json'); const user = await checkCredentials(email, password); if (!user) { return problem(c, { type: problemType('invalid-credentials'), title: 'The email or the password is not correct', status: 400, detail: 'Check both and try again', }); } await openSession(c, user.id); return c.json(user, 200);});checkCredentials(email, password)finds the account and verifies the password with argon2, as in lesson 1.- If it doesn’t match, a
400with Problem DetailsThe standard shape of the body of an error response in an API, written down in RFC 9457: a JSON with type (what kind of problem it is), title (its summary), status (the status code), detail (what happened this time) and instance (which of the times). It’s sent with the content type application/problem+json.Go to definition, the same one for any failure (more on why below). openSession(c, user.id)creates the session and sends its id in the .- The response is the account, the id and the email: never the hash.
The password goes in the body of a POST, never in the URL, which ends up in logs and browser histories.
A long, random id
Section titled “A long, random id”// A week: after that, you have to sign in again.export const SESSION_DURATION = 7 * 24 * 60 * 60; // in seconds
// 32 random bytes (256 bits): nobody can guess it or try them all. base64url writes it with// letters, digits, - and _, which fit in a cookie without escaping anything.// PostgreSQL sets the expiry time: now() plus the duration, the same time as created_at.export async function createSession(userId: number): Promise<string> { const id = randomBytes(32).toString('base64url'); await db.insert(sessions).values({ idHash: hashOfId(id), userId, expiresAt: sql`now() + make_interval(secs => ${SESSION_DURATION})`, }); return id;}
// SHA-256, a fast hash, and here it's fine: the id is random and very long, so there's no list of// likely ids to try, as there is for passwords (lesson 1).const hashOfId = (id: string) => createHash('sha256').update(id).digest();randomBytes(32): 32 bytes from the random generator meant for secrets, the one used to make keys. That’s 256 bits: there are more possible ids than atoms on Earth.toString('base64url')writes those bytes as 43 letters, digits,-and_, which fit in a cookie as they are.db.insert(sessions)stores the id’s hash, whose session it is and until when it’s valid:now()plus a week. The id itself only goes out, to the cookie.
Why so long? In the introduction you requested orders 1 to 25 in less than a second. If sessions were 1, 2, 3…, they would be stolen just as easily. The time or Math.random() won’t do either: they can be predicted.
In the table, only its hash
Section titled “In the table, only its hash”The new table, in migration 006:
CREATE TABLE sessions ( -- bytea: bytes, nothing more. The 32 bytes of the id's SHA-256. It's the primary key: finding a -- session by its hash is instant. id_hash bytea PRIMARY KEY, -- ON DELETE CASCADE: if the account is deleted, its sessions go with it. user_id integer NOT NULL REFERENCES users (id) ON DELETE CASCADE, created_at timestamptz NOT NULL DEFAULT now(), -- After this time, the session is no longer valid, even if the browser still has the cookie. expires_at timestamptz NOT NULL);id_hash bytea: the 32 bytes of the id’s SHA-256 HashA short, fixed-size summary calculated from some data, like a fingerprint. The same data always gives the same hash, and the smallest change gives a completely different one. Git calls each commit by its hash.Go to definition, as the Primary keyThe column, or group of columns, that identifies each row of a table. Its value can’t repeat or be missing, like an order number.Go to definition.ON DELETE CASCADE: if an account is deleted, its sessions go with it.
Why the hash and not the id? Because the id works like a password: whoever has it gets in. Someone who took a copy of the table (a lost backup, a SQL injectionSQL stands for Structured Query Language.An attack that sends a value crafted so that, pasted inside the text of a query, it changes what the query does, such as returning every row or deleting a table. It’s prevented by sending the values separately, as parameters, and never pasting them into the SQL.Go to definition like the ones in lesson 6) with the ids in plain text would get into every account with an open session. With the hash, they wouldn’t: a hash can’t be undone.
And why SHA-256, if in lesson 1 a fast hash was a mistake? There, the danger was trying likely passwords, a list that exists. For a random id there’s no list. And this hash is computed on every request: with argon2, each one would take 20 ms longer.
Every request: from the cookie to the account
Section titled “Every request: from the cookie to the account”This MiddlewareA function a server runs with the requests of the routes it’s registered on (all of them, or only some), before the code that answers them. It can answer the request itself or pass it on to the next one, and it sees the response on its way back. It’s used for what affects many requests, like writing them to the log, granting CORS permission or asking for a credential.Go to definition runs on every route, in src/middleware/session.ts:
// The id arrives in the cookie (a browser) or in the Authorization: Bearer <id> header (a program// that doesn't keep cookies, like a phone app). Both ways say the same: "this is my session".function sessionId(c: Context): string | undefined { return getCookie(c, COOKIE) ?? /^Bearer (\S+)$/.exec(c.req.header('Authorization') ?? '')?.[1];}
// On every request: if it brings a valid session, it leaves its account in c.var.user. If not,// it does nothing: deciding whether a route needs a session is requireIdentity's job.export const loadSession: MiddlewareHandler<Env> = async (c, next) => { const id = sessionId(c); const user = id === undefined ? undefined : await sessionUser(id); if (user) c.set('user', user); await next();};sessionId(c)looks for the id in thesessioncookie and, if it isn’t there, in theAuthorization: Bearer …header, for programs that don’t keep cookies, like a phone app.sessionUser(id)finds out whose account that id’s hash belongs to (see below).c.set('user', user)leaves the account inc.var.userfor the routes (src/env.tstells TypeScript what’s there). Without a session, it does nothing: if a route needs one,requireIdentitydecides.
A query on every request is the price of sessions. In lesson 3, “JWT,” you’ll see who skips it, and at what cost.
The cookie: what each attribute stops
Section titled “The cookie: what each attribute stops”// Each of the cookie's attributes (Phase 2) has its reason:// - HttpOnly: the page's JavaScript can't read it. If someone manages to slip a script into the// page (XSS, lesson 6), they don't take the session with them.// - Secure: it only travels over HTTPS. Current browsers and curl (tested with 8.14) treat// http://localhost as secure, so on your computer it works without HTTPS too. With// http://127.0.0.1 it doesn't: for the browser it's another site, with its own cookies.// - SameSite=Lax: if another site makes the browser send a POST here, the cookie doesn't go// (lesson 7).// - Path=/: it's valid for the whole API.// - Max-Age: the seconds the browser keeps it, the same the session lasts.const ATTRIBUTES = { httpOnly: true, secure: true, sameSite: 'Lax', path: '/' } as const;
// Creates the session and sends its id in the cookie. If the browser brought another session, it's// deleted: after signing in, always a new id. Otherwise, someone who had slipped their id into your// browser before you signed in (session fixation) would have your session as soon as you came in.export async function openSession(c: Context, userId: number) { const previous = sessionId(c); if (previous !== undefined) await deleteSession(previous); const id = await createSession(userId); setCookie(c, COOKIE, id, { ...ATTRIBUTES, maxAge: SESSION_DURATION });}
// When signing out: the row is deleted and the browser is asked to forget the cookie (Max-Age=0).export async function closeSession(c: Context) { const id = sessionId(c); if (id !== undefined) await deleteSession(id); deleteCookie(c, COOKIE, ATTRIBUTES);}You saw the attributes in the Phase 2 lesson on cookies. What each one stops, here:
| Attribute | In the shop |
|---|---|
HttpOnly |
A script slipped into a page of the shop (XSSXSS stands for Cross-Site Scripting.An attack in which a web page includes text someone else wrote, and that text carries JavaScript code that each visitor’s browser runs as if it were the page’s own. It’s prevented by replacing the special characters in each piece of data, like “<”, with a version the browser shows but never reads as code.Go to definition, lesson 6) can’t read the id |
Secure |
The id only travels over HTTPSHTTPS stands for HyperText Transfer Protocol Secure.HTTP inside a TLS connection, usually on port 443. Nobody along the way can read or change the requests and responses, and the browser uses a certificate to check that the server really belongs to the domain.Go to definition: on a coffee shop’s Wi-Fi, nobody reads it on the way |
SameSite=Lax |
Another site can’t make your browser send a POST to the shop with your session: the CSRFCSRF stands for Cross-Site Request Forgery.An attack in which a page makes your browser send a request to a site where you’re logged in, with your cookies, to do something on your behalf, such as changing your email or buying something. CORS doesn’t prevent it, because many requests reach the server even if the page can’t read the response.Go to definition of lesson 7 |
Path=/ |
It’s valid for the whole API |
Max-Age=604800 |
The browser forgets it in a week, which is how long the session lasts |
And Secure without HTTPS, on your computer? Chrome, Firefox and curl treat http://localhost as secure. But http://127.0.0.1:3000 is a different site for the browser, with its own cookies: there it wouldn’t recognize you.
Signing out is deleting the row
Section titled “Signing out is deleting the row”closeSession does two things: it deletes the row from the table (deleteSession) and asks the browser to forget the cookie (deleteCookie, which sends it again, empty and with Max-Age=0).
The one that matters is the first. Deleting the cookie only deletes it from that browser: a copy (from a malicious program, an extension, a curl file) is still valid as long as the row exists.
DELETE /v2/session answers 204 even if there’s no session: the result is the same. And “sign out of all devices” is deleting all of an account’s rows, something worth doing when someone changes their password.
The server decides when it expires
Section titled “The server decides when it expires”Max-Age is a request to the browser, and a copy of the cookie has no reason to obey it. That’s why the server checks expires_at on every request:
// A session's account, or undefined if it doesn't exist or has expired. An expired session is// deleted right then: that way the table doesn't fill up with old sessions (in a big shop, a// process would also delete them every night).export async function sessionUser(id: string): Promise<User | undefined> { const [row] = await db .select({ id: users.id, email: users.email, expiresAt: sessions.expiresAt }) .from(sessions) .innerJoin(users, eq(users.id, sessions.userId)) .where(eq(sessions.idHash, hashOfId(id))); if (row === undefined) return undefined; if (row.expiresAt <= new Date()) { await deleteSession(id); return undefined; } return { id: row.id, email: row.email };}- The
selectjoinssessionswithusers(a Join (combining tables)The part of an SQL query that puts together the rows of two tables that match on a condition, such as each order with its product. If a row matches several in the other table, it comes out once for each one.Go to definition) and searches by the id’s hash. row.expiresAt <= new Date(): if that time has already passed, it isn’t valid, and it’s deleted while we’re at it.
A week is a choice. OWASPOWASP stands for Open Worldwide Application Security Project.An open community, backed by a nonprofit foundation, that publishes free guides and tools for building secure web applications. Its best-known document is the OWASP Top 10, the list of the ten most serious risks for web applications.Go to definition also recommends closing it after a while without use: your bank throws you out in minutes; a social network, in months. The more an account is worth, the shorter the session.
A new id every time you sign in
Section titled “A new id every time you sign in”Session fixation is making the victim sign in with an id the attacker already knows. Many sites give every visitor a session, for the cart, and write the account into it when they sign in. If the id doesn’t change, someone can get one, leave it in Marta’s browser (on a shared computer) and wait: when Marta signs in, that id is her session.
openSession prevents it, in the cookie code: if the request already brought a session, it deletes it and creates another. After signing in, always a new id.
The same error for an email that doesn’t exist
Section titled “The same error for an email that doesn’t exist”// The hash of a random password nobody knows. It makes an email that doesn't exist take the same// time as one that does: without it, the response would arrive 20 ms earlier, and by measuring the// time you'd know which emails have an account.const DUMMY_HASH = await hashPassword(randomBytes(32).toString('hex'));
// Returns the account if the email and the password are its own; if not, undefined, without saying// which of the two fails. An account without a password (it comes in with a provider, lesson 4)// doesn't get in this way either.export async function checkCredentials(email: string, password: string): Promise<User | undefined> { const [row] = await db .select() .from(users) .where(sql`lower(${users.email}) = lower(${email})`); // A password is always verified, whether the account exists or not: the same work, the same time. const correct = await verifyPassword(password, row?.passwordHash ?? DUMMY_HASH); if (row === undefined || row.passwordHash === null || !correct) return undefined; return { id: row.id, email: row.email };}The login must not reveal which emails have an account (user enumeration). It takes two things:
- The same response. An email that doesn’t exist and a wrong password get the same
400with the same body: “The email or the password is not correct.” - The same time. Without an account there would be no hash to verify, and the response would arrive 20 ms earlier.
DUMMY_HASH, the hash of a password nobody knows, makes sure one is always verified.
Why does it matter? Being a customer of a shop is already personal data (think of a pharmacy), and whoever tries stolen passwords can skip the accounts that don’t exist.
One caveat: POST /v2/accounts does say it, with its 409. Big sites always answer the same and send an email; lesson 8, “Rate limiting,” will limit how many times you can ask.
400 when signing in, 401 afterwards, with WWW-Authenticate
Section titled “400 when signing in, 401 afterwards, with WWW-Authenticate”// For the routes that need to know who you are. Without a session, 401 Unauthorized: "I don't// know who you are". A 401 has to say in WWW-Authenticate how to identify yourself (RFC 9110). This// API accepts the session as Bearer, so the Bearer challenge is true: "send Authorization: Bearer// <id>". The browser, which uses the cookie, doesn't need to read it.export const requireIdentity: MiddlewareHandler<Env> = async (c, next) => { if (c.var.user === undefined) { return httpProblem(c, 401, 'Sign in first', { 'WWW-Authenticate': 'Bearer realm="shop-api"', }); } await next();};GET /v2/mewithout a session:401. The standard asks every401to say inWWW-Authenticatehow to identify yourself (lesson 6 of Phase 3). HTTP has no scheme for “send your cookie,” and many APIs with sessions skip the header. The shop sends it without lying: it accepts the same id asAuthorization: Bearer …, soBearer realm="shop-api"(realm, the name of the protected area) promises something true.POST /v2/sessionwith a wrong password:400. A401would ask you to identify yourself, and this route is exactly where you do that. OAuthA standard that lets an app get limited permission on your account with another service, like viewing your photos, without knowing your password. You give the permission on the service’s own website, and the service hands the app a key that opens only that and that you can take back whenever you want.Go to definition answers the same to a wrong password, and so does the webhook signature in Phase 4. Other APIs answer401: what matters is that it’s the same for both failures.
A second factor, when the password is not enough
Section titled “A second factor, when the password is not enough”A stolen password opens the account. Two-step AuthenticationChecking who is making a request, for example with their email and password. It answers “Who are you?”; what that person can do is decided afterward by authorization.Go to definition also asks for something only the person has: a TOTP code, six digits an app computes every 30 seconds from a secret and the time, or a passkey, a key pair like the ones in Phase 0 kept on your device, with nothing to type into a fake site. The session opens after the second step. The shop doesn’t build it; OWASP’s guide explains how.
Try it
Section titled “Try it”The goal: sign in as Marta with curl, find her session in the table, and prove that after signing out a copy of the cookie no longer opens anything. Then, in the browser.
You’re going to reuse a stolen cookie, your own, on localhost. Doing it with someone else’s, on a system that isn’t yours, is a crime.
Write the code
Section titled “Write the code”You start from your project from lesson 1, “Passwords”:
- In
src/schema.ts, thesessionstable. Generate its migration withnpm run db:generate -- --name=sessionsand save it asdb/migrations/006-sessions.sql. - Create
src/sessions.ts,src/env.tsandsrc/middleware/session.ts. - In
src/users.ts,checkCredentials; insrc/schemas.ts,credentialsSchema. - In
src/contract.ts, the three routes; insrc/v2.ts, their functions; insrc/app.ts,app.use(loadSession).
Whatever you haven’t seen here, copy it from the step. The tests come in its folder:
cd ~/backend-course/phase-3curl -O https://backenddesdecero.com/practicas/shop-api/25-sessions.tar.gztar -xzf 25-sessions.tar.gzcd shop-apicp ../25-sessions/test/*.ts test/1. The sessions table
npm run db:migrateWhat you will see:
> shop-api@1.0.0 db:migrate> node --env-file-if-exists=.env scripts/migrate.ts
Applied: 006-sessions.sqlIf you get was not applied, read the PostgreSQL error that comes after it.
2. This lesson's tests
npm test -- test/sessions.test.tsWhat you will see:
> shop-api@1.0.0 test> node --env-file=test/.env --test --test-concurrency=1 test/sessions.test.ts
✔ signing in (with the email in other capitals): 200 with the account; /v2/me recognizes it (217.817444ms)✔ the cookie: a long random id, HttpOnly, Secure, SameSite=Lax, Path=/ and a week (66.636666ms)✔ in the table, only the SHA-256 of the id, and it expires in a week (72.655318ms)✔ a wrong password and an email that does not exist: the same response, without a cookie (132.020073ms)✔ an account without a password (from an identity provider) cannot get in with one (26.363945ms)✔ /v2/me without a session, or with a made-up id: 401 with WWW-Authenticate (9.741385ms)✔ signing out: 204, the cookie is deleted, and the old id is no longer valid even if kept (59.212743ms)✔ an expired session is not valid, and it is deleted (76.591484ms)✔ when signing in, a new id: the one the browser brought is deleted (session fixation) (174.231315ms)ℹ tests 9ℹ suites 0ℹ pass 9ℹ fail 0ℹ cancelled 0ℹ skipped 0ℹ todo 0ℹ duration_ms 3191.27171One test for each idea in the lesson. The outputs are from Node 26 and PostgreSQL 18; your times, ids and dates will be different.
Sign in with curl
Section titled “Sign in with curl”Start the API with npm start and open another terminal in the project folder. Marta signs in with the password you gave her in lesson 1:
3. Signing in
curl -s -i -w '\n' -c cookies.txt --json '{"email":"marta@example.com","password":"a long sentence only I know"}' localhost:3000/v2/sessionWhat you will see:
HTTP/1.1 200 OKcontent-type: application/jsonvary: Originx-request-id: a980cebd-8b89-4aa5-b7fb-ccbcd23ae050set-cookie: session=A4vjwCNur4PcId04eQa48meWarqyfFZ33vHvmsUppUY; Max-Age=604800; Path=/; HttpOnly; Secure; SameSite=Laxcontent-length: 36Date: Wed, 14 Oct 2026 04:42:25 GMTConnection: keep-aliveKeep-Alive: timeout=5
{"id":1,"email":"marta@example.com"}Look at set-cookie: the id, 43 random characters, and the five attributes. -c cookies.txt saves the cookie in a file, as in Phase 2. If you get a 400, check Marta’s password.
4. What curl saved
cat cookies.txtWhat you will see:
# Netscape HTTP Cookie File# https://curl.se/docs/http-cookies.html# This file was generated by libcurl! Edit at your own risk.
#HttpOnly_localhost FALSE / TRUE 1792557745 session A4vjwCNur4PcId04eQa48meWarqyfFZ33vHvmsUppUY#HttpOnly_ in front of localhost isn’t a comment: it marks the cookie as HttpOnly. The fourth column, TRUE, is Secure, and 1792557745 is the expiry: a week later, in seconds since 1970. This file is an open session: whoever has it is Marta.
5. Who am I? With and without the cookie
curl -s -w '\n' -b cookies.txt localhost:3000/v2/mecurl -s -i -w '\n' localhost:3000/v2/meWhat you will see:
{"id":1,"email":"marta@example.com"}HTTP/1.1 401 Unauthorizedcontent-type: application/problem+jsonvary: Originwww-authenticate: Bearer realm="shop-api"x-request-id: 65ada8e7-7d28-4cab-bdcb-98b6fa8f2bb7content-length: 83Date: Wed, 14 Oct 2026 04:42:25 GMTConnection: keep-aliveKeep-Alive: timeout=5
{"type":"about:blank","title":"Unauthorized","status":401,"detail":"Sign in first"}With -b cookies.txt, Marta’s account. Without it, the 401 with its www-authenticate.
Find the session in the table
Section titled “Find the session in the table”6. The session's row
psql -d shop -c "SELECT encode(id_hash, 'hex') AS id_hash, user_id, created_at, expires_at FROM sessions;"What you will see:
id_hash | user_id | created_at | expires_at------------------------------------------------------------------+---------+-------------------------------+-------------------------------3aa9cb38a4213f73cbb1cdee83fb15118ab65dce5ea54bdfe7d53daaa6a2903a | 1 | 2026-10-14 04:42:25.024599+00 | 2026-10-21 04:42:25.024599+00(1 row)encode(…, 'hex') writes the bytes as text. The id from the cookie, A4vjwCNu…, isn’t there. And expires_at is a week after created_at.
Sure that hash is the id’s? Compute it yourself:
7. The id's SHA-256
ID=$(grep session cookies.txt | cut -f7)printf %s "$ID" | shasum -a 256What you will see:
3aa9cb38a4213f73cbb1cdee83fb15118ab65dce5ea54bdfe7d53daaa6a2903a -$(…) stores in ID what the command inside writes: column 7 (cut -f7) of the cookie’s line. printf %s writes it without a line break, which would change the hash. Out comes the one in the table: from the id you get to the hash, and from the hash there’s no way back.
8. The same session, without a cookie
curl -s -w '\n' -H "Authorization: Bearer $ID" localhost:3000/v2/meWhat you will see:
{"id":1,"email":"marta@example.com"}What the WWW-Authenticate promised: the id in Authorization is worth the same as in the cookie.
An email that doesn’t exist and a wrong password
Section titled “An email that doesn’t exist and a wrong password”9. Two failures, one response
curl -s -w ' %{http_code} %{time_total}s\n' --json '{"email":"marta@example.com","password":"some other sentence"}' localhost:3000/v2/sessioncurl -s -w ' %{http_code} %{time_total}s\n' --json '{"email":"nobody@example.com","password":"some other sentence"}' localhost:3000/v2/sessionWhat you will see:
{"type":"https://shop.example/problems/invalid-credentials","title":"The email or the password is not correct","status":400,"detail":"Check both and try again"} 400 0.026844s{"type":"https://shop.example/problems/invalid-credentials","title":"The email or the password is not correct","status":400,"detail":"Check both and try again"} 400 0.020785s%{time_total} is how long the response took. The body and the code, identical; the times, similar. If you repeat it, they jump around, but neither of the two skips the hash.
Sign out, and come back with the copy
Section titled “Sign out, and come back with the copy”Before signing out, copy the cookie file, as whoever stole it from you would:
10. Signing out and reusing the copy
cp cookies.txt copy.txtcurl -s -i -b cookies.txt -c cookies.txt -X DELETE localhost:3000/v2/sessioncurl -s -w '\n' -b copy.txt localhost:3000/v2/meWhat you will see:
HTTP/1.1 204 No Contentvary: Originx-request-id: a62e8a69-4b01-401d-9580-be1d53171758set-cookie: session=; Max-Age=0; Path=/; HttpOnly; Secure; SameSite=LaxDate: Wed, 14 Oct 2026 04:42:36 GMTConnection: keep-aliveKeep-Alive: timeout=5
{"type":"about:blank","title":"Unauthorized","status":401,"detail":"Sign in first"}The DELETE deletes the row, and its Max-Age=0 removes the cookie from cookies.txt. What matters is the last line: the copy, which still has the id, gets a 401. If the route only deleted the cookie, the copy would still be Marta for a week.
Challenge: sign in again with -c cookies.txt, copy the file as before.txt and sign in a second time sending the cookie you already have (-b cookies.txt -c cookies.txt). Does the id change? What does /v2/me answer with before.txt?Show answer
The id changes. With grep session before.txt cookies.txt | cut -f7 you’ll see two different ones, like these:
Q6owc_SNUa-YnjC27m2QywBufrhhzfikTIG25hfgq48I9e8FctNBZN42wzRxLg8nuMlxdeHgiL8NZVmV7Hi7MoAnd curl -s -o /dev/null -w '%{http_code}\n' -b before.txt localhost:3000/v2/me gives 401 (with cookies.txt, 200): openSession deleted the session the request brought. It’s the defense against session fixation.
When you’re done, delete the files with rm cookies.txt copy.txt before.txt: they hold sessions, and they mustn’t end up in Git.
In the browser
Section titled “In the browser”Open Chrome at http://localhost:3000/v2/me: the 401. Open DevToolsThe developer tools that come with browsers such as Chrome or Firefox, opened with F12. Their Network tab shows every request the page makes, with its response and headers; the Console, the page’s errors; and Application (Storage, in Firefox), what the site stores in your browser, such as cookies.Go to definition as in the Phase 2 introduction and type or paste this into the Console (if Chrome doesn’t let you paste, it tells you what to type first to allow it):
await fetch('/v2/session', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: 'marta@example.com', password: 'a long sentence only I know' }) })The console shows a Response with status: 200. Now:
- The cookie. In Application › Cookies ›
http://localhost:3000, thesessionrow, withHttpOnlyandSecurechecked,SameSiteset toLaxand an expiry a week from now. - What JavaScript sees. In the console,
document.cookiegives''. - Who you are. Reload the tab: Marta’s account.
- Signing out.
await fetch('/v2/session', { method: 'DELETE' })givesstatus: 204; the row disappears from Cookies when you refresh the list, and the tab goes back to the401.
We checked it with Chromium 153, driven by Playwright in Docker.
You have already seen it
Section titled “You have already seen it”- “Sign out of all devices”, on Google or Netflix: all your sessions at once, one per browser or app; in the shop, all your rows in
sessions. - “Your session has expired,” on your bank’s website, after a few minutes without touching it: an expiry for inactivity.
- “The email or the password is not correct,” without saying which of the two: on purpose.
Common mistakes
Section titled “Common mistakes”- Storing the id in plain text in the table: store its hash.
- Ids that can be guessed: consecutive numbers, the time or
Math.random(). UserandomBytes(32). - Signing out by deleting only the cookie. Delete the row.
- Trusting
Max-Age. The server checks the expiry. - Keeping the id from before the login. When someone signs in, delete the old one and create another.
- Saying “that email doesn’t exist,” or answering sooner when it doesn’t.
- Keeping the id in
localStorageor in the URL. Any script readslocalStorage, and the URL ends up in logs. It goes in anHttpOnlycookie.
Summary
Section titled “Summary”- Signing in is checking the password once and giving in return a random 32-byte id, in an
HttpOnly,SecureandSameSite=Laxcookie. - The table stores the id’s SHA-256 hash, the account and the expiry: whoever takes it doesn’t have a single session.
- Signing out is deleting the row, and the server checks the expiry: without the row, a copy of the cookie is useless.
- When someone signs in, always a new id (session fixation). And the same error, in the same time, for an email that doesn’t exist and a wrong password.
Did you get it?
Section titled “Did you get it?”To review:
Further reading
Section titled “Further reading”- Session Management Cheat Sheet (OWASP): the id, the cookie, expiry, signing out and fixation.
- Authentication Cheat Sheet (OWASP): includes the error messages that don’t reveal which accounts exist.
- Multifactor Authentication Cheat Sheet (OWASP): TOTP, passkeys and other second factors.
- Set-Cookie (MDN): every attribute of a cookie.
- Cookie helper (Hono):
setCookie,getCookieanddeleteCookie.