Sub topic 5
Session Identifiers and Secure Cookies
This chapter covers how a browser and a server agree on who is making a request. It assumes you know the basics of HTTP requests, responses, headers and cookies. It also assumes you have built a web service or API in some language. You should know roughly what a load balancer does.
The previous chapters defined session state and showed why sticky sessions have limits. Now we look at the piece every session strategy shares: the identifier the client sends with each request, and the cookie that usually carries it.
Why HTTP needs a session identifier
HTTP is stateless by design. Each request stands alone, and the server has no built-in way to know that two requests came from the same person. A session identifier fills this gap. It is a value the server issues after login (or on first visit) and the client sends back with every later request.
The identifier can mean two different things, and the difference shapes the rest of the tutorial:
- A reference. The value is a random string with no meaning of its own. It points to data stored on the server side, such as a Redis key. Whoever receives the request looks the string up.
- A container. The value holds the session data itself, signed so it cannot be altered. No lookup is needed.
Both travel the same way, usually in a cookie. This chapter focuses on the reference style, and on the cookie mechanics that apply to both. The next two chapters cover the shared store and signed tokens in detail.
What makes a good session identifier
When the identifier is a reference, it works like a password for the session. Anyone who holds it can act as the user. So it has two requirements: it must be unpredictable, and it must be long enough that guessing is not feasible.
Use a cryptographic random source
Use your platform's cryptographically secure random generator. In Python that is the secrets module. Do not use random, timestamps, counters, or hashes of user data. Those can be predicted or reproduced.
import secrets
session_id = secrets.token_urlsafe(32)
print(session_id)
print(len(session_id))token_urlsafe(32) draws 32 random bytes, which is 256 bits, and encodes them as URL-safe text of 43 characters. A common guideline is at least 128 bits of entropy (randomness). 256 bits leaves a wide margin.
Keep the identifier meaningless
Do not put a user ID, email, role or timestamp inside a reference identifier. If it carries meaning, an attacker can learn from it or try to construct valid values. The identifier should be a pure lookup key.
Never accept an identifier the server did not issue
If a client sends an unknown session ID, treat the request as unauthenticated. Do not create a session under the client-supplied value. Accepting it enables session fixation, covered below.
How the cookie carries the identifier
The server sends the identifier with a Set-Cookie response header. The browser stores it and attaches it to later requests to the matching site in a Cookie request header.
Set-Cookie: sid=3q2-7wXk...; Path=/; Max-Age=1800; HttpOnly; Secure; SameSite=LaxThe first part, sid=3q2-7wXk..., is the name and value. Everything after it is an attribute that tells the browser how to handle the cookie. Each attribute has a security purpose.
| Attribute | What it does | Threat it reduces |
|---|---|---|
| `HttpOnly` | Hides the cookie from JavaScript (`document.cookie`) | Theft of the session ID by injected scripts (XSS) |
| `Secure` | Sends the cookie only over HTTPS | Interception on plain HTTP connections |
| `SameSite=Lax` | Withholds the cookie on most cross-site requests | Cross-site request forgery (CSRF) |
| `Max-Age` / `Expires` | Sets how long the browser keeps the cookie | Long-lived stolen cookies |
| `Path` | Limits which URL paths receive the cookie | Unneeded exposure to other paths |
| `Domain` | Widens the cookie to subdomains when set | Exposure to sibling subdomains (see below) |
HttpOnly
With HttpOnly, browser scripts cannot read the cookie. The browser still sends it with requests. This does not stop an XSS attack from making requests as the user, because those requests carry the cookie automatically. It does stop the attacker from copying the identifier and using it from another machine. That distinction matters: HttpOnly limits the damage of XSS but does not fix it.
Secure
With Secure, the browser sends the cookie only on HTTPS requests. Without it, a single request over plain HTTP exposes the identifier to anyone on the network path. Pair it with HTTPS on every page, and consider the Strict-Transport-Security header so browsers refuse plain HTTP in the first place.
SameSite
SameSite controls whether the browser attaches the cookie to requests that start on another site.
| Value | Behavior |
|---|---|
| `Strict` | Cookie is sent only for same-site requests. Following a link from another site arrives without the cookie, so the user looks logged out on that first page. |
| `Lax` | Cookie is also sent on top-level navigations that use safe methods like GET, such as clicking a link. It is not sent on cross-site POSTs, images or frames. |
| `None` | Cookie is sent on all cross-site requests. Requires `Secure`. |
Lax is a sensible default for most applications. Use None only when you truly need cross-site use, such as an embedded widget, and add other CSRF defenses. Browsers treat a cookie with no SameSite attribute as Lax in most cases, but set it explicitly so behavior does not depend on the browser.
SameSite is one layer. For state-changing endpoints, keep CSRF tokens or check the Origin header as well. Note that "same-site" means the same registrable domain, so app.example.com and evil.example.com count as the same site.
Lifetime: session cookies and persistent cookies
A cookie with no Max-Age or Expires is a session cookie in the browser sense: the browser discards it when it closes. A cookie with either attribute is persistent and survives restarts until it expires.
Do not confuse this with the server-side session lifetime. The browser may keep a cookie for a week while the server forgets the session after 30 minutes. The server's expiry is the one that counts for security, because the client controls its own cookie. Chapter 8 covers expiry in depth.
Domain and Path
If you omit Domain, the cookie goes only to the exact host that set it. If you set Domain=example.com, every subdomain receives it, including ones run by other teams or hosting user content. Leave Domain off unless several subdomains must share the session.
Cookie name prefixes
Browsers support two name prefixes that enforce attributes:
__Secure-requires theSecureattribute.__Host-requiresSecure,Path=/, and noDomainattribute. This pins the cookie to the exact host and blocks a sibling subdomain from overwriting it.
Set-Cookie: __Host-sid=3q2-7wXk...; Path=/; Max-Age=1800; HttpOnly; Secure; SameSite=LaxThe __Host- prefix is a cheap, strong default for a single-host application.
Setting the cookie from code
Most frameworks have a call that sets these attributes. Here is a minimal example with Flask that combines the identifier generation with the cookie.
import secrets
from flask import Flask, jsonify, make_response, request
app = Flask(__name__)
SESSION_TTL_SECONDS = 1800
@app.post("/login")
def login():
# Credential checking omitted for brevity.
session_id = secrets.token_urlsafe(32)
# Store session_id -> user data on the server side here.
response = make_response(jsonify({"status": "ok"}))
response.set_cookie(
"__Host-sid",
session_id,
max_age=SESSION_TTL_SECONDS,
path="/",
secure=True,
httponly=True,
samesite="Lax",
)
return response
@app.get("/whoami")
def whoami():
session_id = request.cookies.get("__Host-sid")
if session_id is None:
return jsonify({"authenticated": False}), 401
return jsonify({"authenticated": True})Two points to check in any framework. First, the defaults: many frameworks do not set Secure or HttpOnly unless you ask. Second, the settings must be the same on every instance behind the load balancer, so keep them in shared configuration.
Rotation and fixation
An attacker who can plant a known identifier in a victim's browser can wait for the victim to log in, then use the same identifier. This is session fixation. The defense is to issue a new identifier at every privilege change.
def login_user(old_session_id, user_id, store):
# Discard whatever identifier the client arrived with.
if old_session_id is not None:
store.pop(old_session_id, None)
new_session_id = secrets.token_urlsafe(32)
store[new_session_id] = {"user_id": user_id}
return new_session_idRotate on login, on logout, and on privilege changes such as a role upgrade or a password change. Send the new cookie in the response. Later chapters cover rotation and revocation across the different strategies.
Cookies on a multi-instance deployment
Cookies are what make the identifier portable. The browser sends the same cookie to whichever instance the load balancer picks. This has consequences for a stateless design:
- Every instance must be able to interpret the identifier. With a reference, every instance must reach the same store. With a signed token, every instance must hold the same secret.
- Cookie settings must match across instances and versions. During a rolling deploy, old and new versions run at once. If the new version renames the cookie or changes its attributes, users can lose sessions mid-deploy. Change cookie names deliberately and support both names for a transition period.
- Sticky-session cookies are separate. A load balancer may set its own affinity cookie. Treat it as routing metadata, never as an authentication credential.
Size limits and what not to store in a cookie
Browsers cap a cookie at about 4 KB, and they send every matching cookie on every request. A large cookie adds bytes to each request, including requests for images and scripts on the same host. For a reference identifier this is not an issue, since the value is about 43 characters. It becomes a concern with client-side tokens, which later chapters discuss.
Even in a reference design, do not store secrets or personal data in other cookies without a reason. Cookies are visible to the user, appear in browser tools, and may be logged by intermediaries that terminate TLS.
Common errors
- Using a predictable identifier. Sequential numbers, timestamps or
md5(username)can be guessed. Use a cryptographic random source. - Omitting
Securein development and shipping it that way. Use environment configuration so production always sets it. Browsers treatlocalhostas a secure context, so you can usually keepSecureon during local work. - Putting the identifier in the URL. URLs are stored in browser history, logs and
Refererheaders. Use a cookie or anAuthorizationheader. - Skipping rotation at login. This leaves the application open to session fixation.
- Relying on the browser's cookie expiry. The client controls it. Enforce expiry on the server.
- Setting
Domaintoo broadly. A cookie shared with every subdomain is only as safe as the weakest subdomain. - Treating
HttpOnlyas XSS protection. It limits cookie theft, not request forgery from injected scripts.
How the pieces fit together
The sequence below shows a login followed by a request that lands on a different instance.
Neither instance keeps session data in memory. The cookie carries only a key, and the store holds the data. That is the property that lets you add, remove or replace instances freely.
Checking your cookie
You can verify the header from the command line.
curl -i -X POST https://app.example.com/login \
-d 'username=demo&password=demo'In the output, look for one Set-Cookie line and confirm it includes HttpOnly, Secure, SameSite, and an expiry you expect. If the name starts with __Host-, confirm there is no Domain attribute and that Path=/ is present. A browser silently rejects a __Host- cookie that breaks those rules, so a missing session is often a sign the attributes are wrong.
Summary of settings
For a typical single-host web application using a session reference, start with these settings and loosen them only for a reason:
- A 256-bit random identifier from a cryptographic generator.
- The name
__Host-sid, withPath=/and noDomain. HttpOnly,SecureandSameSite=Lax.- A
Max-Agethat matches or is shorter than the server-side lifetime. - A new identifier at login, logout and privilege changes.
- CSRF tokens or
Originchecks on state-changing requests.
Exercise
A teammate sets a session cookie as Set-Cookie: sid=abc; Domain=example.com; Max-Age=604800, and the identifier is md5(user_id + timestamp). List the problems and give a corrected header and identifier approach.
Show answer
Problems: (1) the identifier is derived from guessable inputs, so an attacker can predict or brute-force it; (2) there is no HttpOnly, so injected scripts can read it; (3) there is no Secure, so it can be sent over plain HTTP; (4) there is no SameSite, so cross-site behavior depends on the browser; (5) Domain=example.com shares the cookie with every subdomain; (6) a seven-day Max-Age is long for a session, and the server should enforce its own shorter expiry. Fix: generate the identifier with a cryptographic random source such as secrets.token_urlsafe(32), and send Set-Cookie: __Host-sid=<random>; Path=/; Max-Age=1800; HttpOnly; Secure; SameSite=Lax, with no Domain attribute. Also issue a new identifier at login to prevent fixation.
Exercise
After a rolling deploy, some users are logged out. The new version renamed the cookie from sid to __Host-sid. Why does this happen, and how do you avoid it?
Show answer
During the deploy, old and new instances run together. A request carrying only the old sid cookie that reaches a new instance finds no __Host-sid, so the new instance treats the user as unauthenticated. Once the old cookie is no longer read anywhere, users also lose their sessions permanently. To avoid this, have the new version accept both names for a transition period, reading __Host-sid first and falling back to sid. When it finds a session under the old name, it can issue the new cookie and later retire the old name.
Exercise
Does HttpOnly stop an XSS attacker from performing actions as the logged-in user? Explain.
Show answer
No. HttpOnly stops scripts from reading the cookie value, so the attacker cannot copy the identifier and use it elsewhere. But a script running in the page can still send requests to your site, and the browser attaches the cookie automatically. The attacker can therefore act as the user while the page is open. Preventing XSS itself (output encoding, a Content-Security-Policy) is still necessary.