Sub topic 5
Session Identifiers and Secure Cookies
This chapter assumes you know basic HTTP, including request and response headers, and that you have built a small web service. It covers how a browser and a server agree on who is making a request when the server keeps no per-connection memory.
Why a session needs an identifier
HTTP is stateless. Each request arrives on its own, and nothing in it says "this is the same user as a moment ago." To build a login or a shopping cart, the client must send something with every request that links it to earlier ones.
That something is a session identifier (session ID). It is a value the server hands out after login. The browser returns it on each later request. Where the server then finds the session data is a separate choice, and later chapters cover it. This chapter covers the identifier and the cookie that carries it.
What makes a good identifier
If someone guesses or steals a valid ID, they become that user. Two rules follow.
- Make it unpredictable. Use a cryptographically secure random generator, not a counter, a timestamp, or
random. Use at least 128 bits of randomness. In Python,secrets.token_urlsafe(32)gives 256 bits. - Make it meaningless. The ID should be a lookup key or an opaque token. Do not put the user name or a role in it.
The create_session function from the shared-store example later in this tutorial follows both rules:
import secrets
session_id = secrets.token_urlsafe(32)
print(len(session_id), session_id)Sending the identifier in a cookie
A cookie is a small value the server asks the browser to store and send back on later requests to the same site. The server sets it with a Set-Cookie response header:
Set-Cookie: sid=3q2-7wXk...; Path=/; Max-Age=1800; HttpOnly; Secure; SameSite=LaxEach attribute has a job.
| Attribute | Effect | Threat it reduces |
|---|---|---|
| `HttpOnly` | JavaScript cannot read the cookie through `document.cookie` | Theft by injected scripts (XSS) |
| `Secure` | Browser sends the cookie only over HTTPS | Sniffing on plain HTTP |
| `SameSite=Lax` | Browser withholds the cookie on most cross-site requests, except top-level navigations such as link clicks | Cross-site request forgery (CSRF) |
| `Max-Age=1800` | Cookie is discarded after 1800 seconds | Long-lived stolen cookies |
| `Path=/` | Cookie is sent for every path on the site | Not a security control; scopes the cookie |
SameSite=Strict withholds the cookie on all cross-site requests, including link clicks. This is safer but means a user who follows a link to your site from elsewhere arrives logged out. Lax is a common default for that reason.
Setting the cookie in code
Here is a minimal Flask handler that sets the cookie with these attributes.
from flask import Flask, make_response
app = Flask(__name__)
@app.post("/login")
def login():
session_id = "replace-with-a-value-from-create_session"
resp = make_response({"ok": True})
resp.set_cookie(
"sid",
session_id,
max_age=1800,
httponly=True,
secure=True,
samesite="Lax",
path="/",
)
return respNote that secure=True means a browser will not send the cookie back over plain http://. When you test locally without HTTPS, most browsers treat localhost as an exception, but other hostnames do not get one.
Why this fits stateless services
The cookie travels with every request, so any instance behind the load balancer receives the identifier. The instance does not need to remember the browser. It only needs a way to resolve the identifier into session data, which is the job of a shared store or a signed token. The cookie is the transport. The next chapters decide what it points to.
Common errors
- Reusing the ID after login. If the same ID exists before and after authentication, an attacker who planted it beforehand (session fixation) gains the logged-in session. Issue a new ID at login.
- Putting the ID in the URL. URLs end up in logs, browser history and
Refererheaders. Use a cookie. - Omitting
Securein production because it was off in development. - Storing sensitive data in the cookie itself without signing or encryption. A plain cookie value is fully controlled by the user.
- Setting a very broad
Domain. A cookie scoped toexample.comis also sent to every subdomain, including ones you may not control well.
Exercise
A developer sets Set-Cookie: sid=abc123; Path=/ over HTTPS and generates IDs by incrementing a counter. Name three problems and the fix for each.
Show answer
(1) Missing HttpOnly lets injected scripts read the cookie; add HttpOnly. (2) Missing Secure lets the cookie be sent over plain HTTP if the user visits an http:// URL; add Secure. (3) Counter-based IDs are guessable, so an attacker can try neighbouring values; generate at least 128 random bits with a secure generator such as secrets.token_urlsafe(32). Also worth adding: SameSite=Lax and a Max-Age.
Exercise
Why must the server issue a new session ID when a user logs in, even if an anonymous session already existed?
Show answer
An attacker may have planted or learned the pre-login ID (session fixation). If the same ID continues after authentication, the attacker's copy becomes a logged-in session. A fresh ID invalidates anything known before login.