Skip to content

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

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

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.

Signing in: the password once, and an id in return

Section titled “Signing in: the password once, and an id in return”
  1. Marta's browser → The shop's APIPOST /v2/session
    the email and the password
  2. The shop's API → PostgreSQLThe account for that email, with its hash
  3. The shop's APIargon2: does the password match?
  4. The shop's API → PostgreSQLINSERT INTO sessions
    the hash of a new id
  5. The shop's API → Marta's browser200 OK
    Set-Cookie: session=A4vjwCNu…
  6. Marta's browser → The shop's APIGET /v2/me
    Cookie: session=A4vjwCNu…
  7. The shop's API → PostgreSQLWhose is this id's hash?
  8. 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:

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 400 with 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 CookieA small piece of data, with a name and a value, that a server asks the browser to keep with the Set-Cookie header. The browser sends it back in the Cookie header of its next requests to that site, and that’s how the server recognizes the same visitor.Go to definition.
  • 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.

src/sessions.ts
// 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.

The new table, in migration 006:

db/migrations/006-sessions.sql
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.

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:

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 the session cookie and, if it isn’t there, in the Authorization: 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 in c.var.user for the routes (src/env.ts tells TypeScript what’s there). Without a session, it does nothing: if a route needs one, requireIdentity decides.

A query on every request is the price of sessions. In lesson 3, “JWT,” you’ll see who skips it, and at what cost.

src/middleware/session.ts
// 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.

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.

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:

src/sessions.ts
// 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 select joins sessions with users (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.

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”
src/users.ts
// 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 400 with 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”
src/middleware/session.ts
// 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/me without a session: 401. The standard asks every 401 to say in WWW-Authenticate how 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 as Authorization: Bearer …, so Bearer realm="shop-api" (realm, the name of the protected area) promises something true.
  • POST /v2/session with a wrong password: 400. A 401 would 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 answer 401: 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.

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.

You start from your project from lesson 1, “Passwords”:

  1. In src/schema.ts, the sessions table. Generate its migration with npm run db:generate -- --name=sessions and save it as db/migrations/006-sessions.sql.
  2. Create src/sessions.ts, src/env.ts and src/middleware/session.ts.
  3. In src/users.ts, checkCredentials; in src/schemas.ts, credentialsSchema.
  4. In src/contract.ts, the three routes; in src/v2.ts, their functions; in src/app.ts, app.use(loadSession).

Whatever you haven’t seen here, copy it from the step. The tests come in its folder:

Ventana de terminal
cd ~/backend-course/phase-3
curl -O https://backenddesdecero.com/practicas/shop-api/25-sessions.tar.gz
tar -xzf 25-sessions.tar.gz
cd shop-api
cp ../25-sessions/test/*.ts test/

1. The sessions table

Ventana de terminal
npm run db:migrate

What you will see:

> shop-api@1.0.0 db:migrate
> node --env-file-if-exists=.env scripts/migrate.ts
Applied: 006-sessions.sql

If you get was not applied, read the PostgreSQL error that comes after it.

2. This lesson's tests

Ventana de terminal
npm test -- test/sessions.test.ts

What 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.27171

One test for each idea in the lesson. The outputs are from Node 26 and PostgreSQL 18; your times, ids and dates will be different.

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

Ventana de terminal
curl -s -i -w '\n' -c cookies.txt --json '{"email":"marta@example.com","password":"a long sentence only I know"}' localhost:3000/v2/session

What you will see:

HTTP/1.1 200 OK
content-type: application/json
vary: Origin
x-request-id: a980cebd-8b89-4aa5-b7fb-ccbcd23ae050
set-cookie: session=A4vjwCNur4PcId04eQa48meWarqyfFZ33vHvmsUppUY; Max-Age=604800; Path=/; HttpOnly; Secure; SameSite=Lax
content-length: 36
Date: Wed, 14 Oct 2026 04:42:25 GMT
Connection: keep-alive
Keep-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

Ventana de terminal
cat cookies.txt

What 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

Ventana de terminal
curl -s -w '\n' -b cookies.txt localhost:3000/v2/me
curl -s -i -w '\n' localhost:3000/v2/me

What you will see:

{"id":1,"email":"marta@example.com"}
HTTP/1.1 401 Unauthorized
content-type: application/problem+json
vary: Origin
www-authenticate: Bearer realm="shop-api"
x-request-id: 65ada8e7-7d28-4cab-bdcb-98b6fa8f2bb7
content-length: 83
Date: Wed, 14 Oct 2026 04:42:25 GMT
Connection: keep-alive
Keep-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.

6. The session's row

Ventana de terminal
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

Ventana de terminal
ID=$(grep session cookies.txt | cut -f7)
printf %s "$ID" | shasum -a 256

What 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

Ventana de terminal
curl -s -w '\n' -H "Authorization: Bearer $ID" localhost:3000/v2/me

What 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

Ventana de terminal
curl -s -w ' %{http_code} %{time_total}s\n' --json '{"email":"marta@example.com","password":"some other sentence"}' localhost:3000/v2/session
curl -s -w ' %{http_code} %{time_total}s\n' --json '{"email":"nobody@example.com","password":"some other sentence"}' localhost:3000/v2/session

What 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.

Before signing out, copy the cookie file, as whoever stole it from you would:

10. Signing out and reusing the copy

Ventana de terminal
cp cookies.txt copy.txt
curl -s -i -b cookies.txt -c cookies.txt -X DELETE localhost:3000/v2/session
curl -s -w '\n' -b copy.txt localhost:3000/v2/me

What you will see:

HTTP/1.1 204 No Content
vary: Origin
x-request-id: a62e8a69-4b01-401d-9580-be1d53171758
set-cookie: session=; Max-Age=0; Path=/; HttpOnly; Secure; SameSite=Lax
Date: Wed, 14 Oct 2026 04:42:36 GMT
Connection: keep-alive
Keep-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-YnjC27m2QywBufrhhzfikTIG25hfgq48
I9e8FctNBZN42wzRxLg8nuMlxdeHgiL8NZVmV7Hi7Mo

And 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.

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:

  1. The cookie. In Application › Cookies › http://localhost:3000, the session row, with HttpOnly and Secure checked, SameSite set to Lax and an expiry a week from now.
  2. What JavaScript sees. In the console, document.cookie gives ''.
  3. Who you are. Reload the tab: Marta’s account.
  4. Signing out. await fetch('/v2/session', { method: 'DELETE' }) gives status: 204; the row disappears from Cookies when you refresh the list, and the tab goes back to the 401.

We checked it with Chromium 153, driven by Playwright in Docker.

  • “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.
  • Storing the id in plain text in the table: store its hash.
  • Ids that can be guessed: consecutive numbers, the time or Math.random(). Use randomBytes(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 localStorage or in the URL. Any script reads localStorage, and the URL ends up in logs. It goes in an HttpOnly cookie.
  • Signing in is checking the password once and giving in return a random 32-byte id, in an HttpOnly, Secure and SameSite=Lax cookie.
  • 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.
A colleague suggests storing each session’s id as it is in the table: “it’s random, it isn’t a password.” Months later, a backup of the database is lost. What can whoever finds it do?

Passwords are stored with argon2, a slow hash. Why is the session id stored with SHA-256, which is fast?

Marta signs in to the shop from a library computer. When she leaves, she clicks “Sign out”, and the site only deletes the cookie from that browser. Someone had copied the cookie a while earlier. Is the copy any use to them?

In another API, an email that doesn’t exist gets “There is no account with that email,” and a wrong password, “Incorrect password.” What’s the problem?

A shop gives every visitor a session for the cart and, when they sign in, writes their account into that same session, without changing the id. What risk does it run?

Someone manages to slip a script into a page of the shop, and the script tries to read the session cookie with document.cookie. Which attribute stops it?

phase-6 · lesson 2/9