Skip to lesson

Practice: cookies, sessions and tokens

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

ShopLite is going live with a website, an API and a phone app. Before it does, four decisions need an answer: which cookie attributes to set, whether two URLs share an origin, sessions or tokens for each client, and what CORS allows.

Picking cookie attributes for a case

Choose each cookie attribute by asking one question, then check the choice against a real Set-Cookie header.

Example 1 · A login-style cookie with all its attributes

Terminal
curl -i -c jar.txt "https://httpbin.org/response-headers?Set-Cookie=SID=abc123;%20Path=/;%20HttpOnly;%20Secure;%20SameSite=Lax;%20Max-Age=1800"cat jar.txt
Sample output
$ curl -i -c jar.txt "https://httpbin.org/response-headers?Set-Cookie=SID=abc123;%20Path=/;%20HttpOnly;%20Secure;%20SameSite=Lax;%20Max-Age=1800"
HTTP/1.1 200 OK
Date: Fri, 16 Oct 2026 02:43:51 GMT
Content-Type: application/json
Content-Length: 154
Connection: keep-alive
Server: gunicorn/19.9.0
Set-Cookie: SID=abc123; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=1800
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true

{
  "Content-Length": "154", 
  "Content-Type": "application/json", 
  "Set-Cookie": "SID=abc123; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=1800"
}

$ cat jar.txt
# Netscape HTTP Cookie File
# https://curl.se/docs/http-cookies.html
# This file was generated by libcurl! Edit at your own risk.

#HttpOnly_httpbin.org	FALSE	/	TRUE	1792120429	SID	abc123

What this code does

  • httpbin's /response-headers sent the exact cookie asked for: HttpOnly; Secure; SameSite=Lax; Max-Age=1800, a 30-minute login cookie for the whole site.
  • The jar shows the #HttpOnly_ prefix, TRUE for Secure and an expiry 1800 seconds after the request. Try it yourself with your own values.

Must page scripts read the cookie? If not, add HttpOnly. Can it travel over plain HTTP? Never for anything private, so add Secure. Should other sites be able to trigger requests that carry it? Usually not, so use SameSite=Lax, or Strict for banking-style pages.

Then choose the lifetime and scope. A login cookie is a session cookie or lasts a few hours, with Path=/ and no Domain. A harmless preference such as a theme may last months and may be readable by scripts.

Same origin or cross-origin: the three-part test

Compare scheme, host and port, then see why an API that trusts every origin is risky for logged-in users.

Example 2 · An API that trusts every origin

Terminal
curl -i -H "Origin: https://evil.example" https://httpbin.org/cookies
Sample output
HTTP/1.1 200 OK
Date: Fri, 16 Oct 2026 03:00:54 GMT
Content-Type: application/json
Content-Length: 20
Connection: keep-alive
Server: gunicorn/19.9.0
Access-Control-Allow-Origin: https://evil.example
Access-Control-Allow-Credentials: true

{
  "cookies": {}
}

What this code does

  • httpbin copies whatever Origin arrives into Access-Control-Allow-Origin and adds Access-Control-Allow-Credentials: true. For a public test service with no user data, that is fine.
  • On an API with logins, the same two headers would let evil.example read a logged-in user's data through their browser. A real API checks the origin against an exact list first.

Compare scheme, host and port, in that order, using the default port when none is written (80 for http, 443 for https). Any difference makes the call cross-origin, and then the server must allow the page's origin with CORS.

A common mistake is to allow every origin, or to copy back whatever Origin arrives together with Access-Control-Allow-Credentials: true. That undoes the protection for logged-in users. Public test services do it on purpose; a real API must keep an exact list.

Sessions or tokens: matching the design to the client

Compare the two login styles on the wire: what each one returns and who stores what.

Example 3 · The two login styles on the wire

Runs in: the demo login server on localhost:8080

Terminal
curl -i -d "username=asha" -d "password=campus123" http://localhost:8080/logincurl -i -d "username=asha" -d "password=campus123" http://localhost:8080/api/login
Sample output
$ curl -i -d "username=asha" -d "password=campus123" http://localhost:8080/login
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 28
Connection: close
Date: Fri, 16 Oct 2026 03:15:59 GMT
Set-Cookie: SID=aecdce460d0e53b56edf361e465b6534; Path=/; HttpOnly; Secure; SameSite=Lax

{"message":"Welcome, asha"}

$ curl -i -d "username=asha" -d "password=campus123" http://localhost:8080/api/login
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 301
Connection: close
Date: Fri, 16 Oct 2026 03:16:01 GMT

{"accessToken":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhc2hhIiwibmFtZSI6IkFzaGEgVmVybWEiLCJyb2xlIjoic3R1ZGVudCIsImlhdCI6MTc5MjEyMDU2MSwiZXhwIjoxNzkyMTIxNDYxfQ.XshEwqtv8zN16onWK1TtNP3Klxp2JGV8CSn7lUppd4I","tokenType":"Bearer","expiresIn":900,"refreshToken":"vNd08fCR2pU4A3Y4RfiLp_8JBOVeszyV"}

What this code does

  • The session login (/login) returns a small body and a Set-Cookie with only a random id; the user data stays on the server, and the browser will send the cookie by itself.
  • The token login (/api/login) sets no cookie. It returns the signed JWT and a refresh token in the body, and the client must store them and add Authorization: Bearer itself.

A browser app on one site fits cookie sessions: the browser stores and sends the cookie, HttpOnly keeps it away from scripts, and logout deletes the session at once. Mobile apps, command-line tools and other servers fit bearer tokens: they add a header easily and keep the token in secure storage.

Many real products use both: cookie sessions for their website and short-lived tokens with refresh tokens for their app and public API, all on the same user accounts.

Explaining it in an interview

Keep each answer to the definition, the reason and one example. These four come up most often.

  • Cookie vs session: a cookie is the client-side carrier; a session is server-side data that the cookie's id points to.
  • Session vs JWT: a session lives on the server and ends at once on logout; a JWT carries signed claims and lasts until it expires.
  • What CORS protects: users in a browser, from other websites reading responses with their cookies. It is not a lock on the API.
  • CSRF vs CORS: CSRF is an attack that sends a forged request with your cookies; CORS controls reading responses. SameSite and CSRF tokens stop CSRF; CORS does not.

Finish up

Mark complete & continue

Next: Mini project: follow a login with curl