HTTP requests arrive separately, but an application may need to recognize a signed-in user across many of them. One design stores session state on the server and gives the browser an opaque session identifier in a cookie. The identifier connects a request to a server-side record; it is not itself proof that the requested action is permitted.
1. Trace a session as a server-side state machine
Definition 8.2.1
(Session)
A session is a server-side record that links a series of requests to one authenticated account. The browser holds only an opaque identifier, usually in a cookie, and returns it with each request. The identifier is a bearer secret: whoever presents a valid copy is treated as that session. The record, not the cookie, carries the state (active, expired or revoked) and the expiry time.
Assume a service has the following explicit contract. After successful authentication it issues a fresh unpredictable identifier, stores a record mapping it to the account with an expiry, and sends the identifier in a cookie. For every protected request, the server looks up the identifier, checks that the record is active and unexpired using server-side time, identifies the account, and then checks permission for the specific operation and resource. A session is valid only while server time is strictly before its expiry. Unknown, revoked and expired identifiers do not authenticate a request. The exact error response is an endpoint policy; the state distinction is what matters here.
| State | How it is entered | Effect on a request that presents the identifier |
|---|---|---|
| Active | Issued after successful authentication | Identifies the account; the permission check still follows |
| Expired | Server time reaches the expiry time | Does not authenticate; the record can be deleted |
| Revoked | Logout, password change or administrator action | Does not authenticate |
| Unknown | Never issued, or already deleted | Does not authenticate |
The worked-examples section traces a concrete timeline through these states.
The browser cookie and the server record are different objects. Clearing the cookie in one browser helps that browser stop sending it, but a copied identifier can remain usable until the server revokes the corresponding session or it expires. Conversely, a server can reject an expired identifier even if a client still sends the cookie. A browser's expiration settings are not a substitute for server-side expiration.
Common mistake
(Letting the expiry instant through)
The contract says a session is valid only while server time is strictly before its expiry. A check written as if (now > record.expiresAt) rejects a session only after the expiry, so a request at exactly 09:30:00 against an expiry of 09:30:00 still authenticates. The check must reject when now >= record.expiresAt, as lookup does, so that the boundary instant belongs to the expired state.
2. Cookie attributes and their limits
For illustration, a server might send a session cookie with Secure, HttpOnly, and SameSite=Lax, choosing its scope and lifetime for the actual deployment. Secure restricts sending the cookie to requests over secure channels (HTTPS), with browser-specific exceptions such as localhost; HttpOnly prevents ordinary JavaScript cookie APIs from reading that cookie. Neither guarantees that malicious code running in the page cannot cause an authenticated action. SameSite limits cookie sending in some cross-site situations, but is only part of a CSRF defense. A cookie-authenticated state-changing endpoint also needs protections appropriate to its deployment, such as a validated CSRF token and origin checks. Cookie attributes do not replace server authorization.
A concrete header shows where each attribute sits. The identifier is a placeholder; a real one is long and unpredictable, and must never appear in logs or notes.
Set-Cookie: sid=<opaque identifier>; Max-Age=1800; Path=/; HttpOnly; Secure; SameSite=Lax
HttpOnlyhides the cookie fromdocument.cookie, but the browser still sends it, so script injected into the page can still cause authenticated requests.Secureallows the browser to send the cookie only over HTTPS, with the browser-specific exception for localhost noted above.SameSite=Strictwithholds the cookie from every cross-site request.Laxalso sends it on top-level navigations that use a safe method such asGET, but withholds it on cross-site subrequests and form posts.Nonesends it cross-site and requiresSecure. A missing attribute is treated asLaxby some browsers, a default that should not be relied on. The unit of comparison is the site, which ignores the port and the subdomain, soapp.example.testandapi.example.testare same-site even though they are different origins.Max-Age(orExpires) sets how long the browser keeps the cookie. Without either it is a session cookie, which the browser discards when it decides its browsing session has ended. This is the browser's copy only; the server's own expiry is separate.PathandDomainset the scope. With noDomain, the cookie is host-only and goes to the exact host that set it. The name prefix__Host-makes browsers insist onSecure,Path=/and noDomain.- To delete a cookie, the server sends
Set-Cookiewith the same name,PathandDomainandMax-Age=0. A mismatchedPathleaves the original cookie in place.
Counterexample mode
HttpOnly does not make a predictable identifier safe
Claim: since the session cookie is HttpOnly, scripts cannot read it, so the identifier may be an incrementing counter, String(nextSid++). An attacker logs in with their own account and receives sid=1041. The attacker then sends Cookie: sid=1040 and Cookie: sid=1039 by hand, from a command-line client that ignores HttpOnly entirely. Each identifier that belongs to an active session is accepted and the attacker is treated as that other user. HttpOnly limits what page scripts can read; it does nothing against guessing. The identifier must come from a cryptographically secure generator with enough bits, such as crypto.randomBytes(32) in the login handler below, so that an unissued identifier cannot be found by trial.
3. Rotation and concurrent requests
A service can reduce session-fixation risk by issuing a new identifier after a successful login and invalidating the old anonymous identifier, rather than granting the old identifier authenticated authority. The exact transition and what happens to requests already in flight must be defined by the server. For example, under a policy with no grace period, an old identifier presented to a new protected request after the transition is rejected. An identifier is a bearer secret: possession of a still-valid copied identifier may let another client use that session, so examples must not put real tokens in logs or teaching materials.
Logout also has a concurrency boundary. A request may have passed an authentication check before logout but complete later. Merely observing its response after logout does not establish when the server committed its work. If the application promises that no previously uncommitted protected write can commit after logout completes, it needs a design that enforces that ordering, for example an appropriate transaction or synchronization between revocation and the final authorization check and write. This is a stronger contract than simply deleting a browser cookie, and it must be tested against the actual storage and concurrency model.
4. Authentication and authorization on every request
Two questions follow every protected request. Authentication asks who sent it: the session lookup answers, and a failure (no cookie, an unknown, expired or revoked identifier) is usually reported as 401. Authorization asks whether that account may perform this operation on this resource, and a failure is usually reported as 403. The order is fixed, since a permission check needs an identity first. The second question must be asked on every request, because a valid session says nothing about which notes belong to the caller. Some applications answer 404 rather than 403 for another user's resource so as not to reveal that it exists. That is a policy choice, not a rule.
Common mistake
(Treating a valid session as permission)
A handler that is protected only by requireLogin and then runs notes.delete(req.params.id) lets user 7, whose session is perfectly valid, delete note 9, which belongs to user 8. The session answers who is asking; it says nothing about which notes that person may change. Compare the note's owner with req.userId inside every handler that acts on a resource, and answer 403 (or 404 where the existence of the note should stay hidden) when they differ.
5. Worked examples
Worked example 8.2.2
(A session timeline under the state-machine contract)
Session s1 is created at 09:00 with an absolute expiry of 09:30, both in server time. Each row below is one request or event.
| Time | Event | Server decision |
|---|---|---|
| 09:00 | Login succeeds; s1 is stored with expiry 09:30 | Cookie issued |
| 09:10 | GET /notes with s1 | Active: authenticated as the account |
| 09:11 | PATCH /notes/9, a note owned by another user | Authenticated but not permitted: 403 |
| 09:12 | POST /logout with s1 | Record revoked; cookie cleared in this browser |
| 09:13 | GET /notes with a copied s1 | Revoked: 401 |
The 09:11 row shows that authentication and authorization are separate: the identity was accepted and the operation was still refused. The 09:13 row shows why the server record matters. Clearing the cookie in one browser did nothing to a copy of the identifier held elsewhere; only the server-side revocation makes the copy useless.
Now take the same session without any logout. A request at 09:29:59 finds the session active, because server time is strictly before the expiry. A request at 09:30:00 is not strictly before it, so the session is expired and is rejected with 401, whatever the browser still holds. The browser's Max-Age is only a convenience for the client; the server decides.
Worked example 8.2.3
(Login that rotates the identifier, and logout that revokes)
The program below implements the contract with an in-memory Map. It is an illustrative sketch that assumes the cookie-parser and express packages and a verifyCredentials function; it has not been deployed, and a real service needs a shared store, because a Map is lost on restart and is not shared between processes.
import crypto from "node:crypto";
import express from "express";
import cookieParser from "cookie-parser";
const app = express();
app.use(express.json());
app.use(cookieParser());
const SESSION_MS = 30 * 60 * 1000;
const sessions = new Map(); // sid -> { userId, expiresAt }; lost on restart
const cookieOptions = { httpOnly: true, secure: true, sameSite: "lax", path: "/" };
function lookup(sid, now) {
const record = sessions.get(sid);
if (!record) return null;
if (now >= record.expiresAt) {
sessions.delete(sid);
return null;
}
return record;
}
app.post("/login", async (req, res) => {
// verifyCredentials is assumed to compare a salted password hash
// and return the account id, or null.
const userId = await verifyCredentials(req.body.username, req.body.password);
if (userId === null) {
return res.status(401).json({ error: "Wrong username or password" });
}
if (req.cookies.sid) sessions.delete(req.cookies.sid); // discard the old identifier
const sid = crypto.randomBytes(32).toString("hex");
sessions.set(sid, { userId, expiresAt: Date.now() + SESSION_MS });
res.cookie("sid", sid, { ...cookieOptions, maxAge: SESSION_MS });
res.status(200).json({ id: userId });
});
app.post("/logout", (req, res) => {
sessions.delete(req.cookies.sid);
res.clearCookie("sid", cookieOptions);
res.status(204).end();
});
A successful login exchange looks like this; the identifier is shown as a placeholder.
POST /login HTTP/1.1
Host: app.example.test
Content-Type: application/json
{"username":"ada","password":"example-password"}
HTTP/1.1 200 OK
Set-Cookie: sid=<64 hexadecimal characters>; Max-Age=1800; Path=/; HttpOnly; Secure; SameSite=Lax
Content-Type: application/json; charset=utf-8
{"id":7}
Trace the login handler. express.json() parses the body, and verifyCredentials returns the account id 7; a failure would produce 401 and no cookie at all. If the request already carried an anonymous sid, the handler deletes that record, so an identifier planted in the browser before login can never become an authenticated one. This is the defense against session fixation. A new identifier is drawn from crypto.randomBytes(32), which gives 256 bits from a cryptographically secure generator. The record stores the account and a server-side expiry. res.cookie then sends the identifier with HttpOnly, Secure, SameSite=Lax, Path=/ and a lifetime of maxAge milliseconds, which Express writes as a Max-Age in seconds; Express may add an Expires date as well.
The logout handler removes the record first and then asks the browser to drop its copy. res.clearCookie must repeat the Path, Secure and related options used when setting, or the browser may keep the original. The order matters: the record deletion is what ends the session, and the cleared cookie is only housekeeping.
Worked example 8.2.4
(A protected route: 401, 403, 404 and 204)
Reuse lookup from the previous example and add a guard and a protected route. Assume notes 5 and 9, where note 5 is owned by user 7 and note 9 by user 8.
function requireLogin(req, res, next) {
const record = lookup(req.cookies.sid, Date.now());
if (!record) return res.status(401).json({ error: "Sign in required" });
req.userId = record.userId;
next();
}
// notes: Map of id -> { id, ownerId, title }
app.delete("/notes/:id", requireLogin, (req, res) => {
const note = notes.get(req.params.id);
if (!note) return res.status(404).json({ error: "Note not found" });
if (note.ownerId !== req.userId) {
return res.status(403).json({ error: "You do not own this note" });
}
notes.delete(note.id);
res.status(204).end();
});
| Request | Path through the code | Response |
|---|---|---|
DELETE /notes/5 with no cookie | lookup(undefined, ...) finds no record | 401 |
DELETE /notes/5, sid expired 30 seconds ago | Record found but not before expiry; deleted | 401 |
DELETE /notes/9, valid sid of user 7 | Authenticated; note exists; owner is 8, not 7 | 403 |
DELETE /notes/5, valid sid of user 7 | Authenticated; owner matches | 204, note removed |
DELETE /notes/77, valid sid of user 7 | Authenticated; no such note | 404 |
Each row stops at the first check that fails, and the checks run in a fixed order: identity, existence, ownership. Placing requireLogin before the handler means the handler can assume req.userId is set. The ownership comparison is the authorization step and must run for every request: the valid cookie of user 7 proves who is asking, not that note 9 is theirs. Checking existence before ownership reveals that note 9 exists to someone who does not own it, which is acceptable here but could be hidden by answering 404 for both cases.
6. Practice
Quick check
(Cookie attributes)
Name the attribute that (a) keeps document.cookie from reading the cookie, (b) stops the browser sending it over plain HTTP, (c) makes the browser withhold it on a cross-site form post while still sending it on a top-level link click, (d) sets how long the browser keeps it.
Solution
(a) HttpOnly. (b) Secure. (c) SameSite=Lax; Strict would withhold it on the link click as well. (d) Max-Age or Expires; without them the cookie is a session cookie that the browser discards at the end of its browsing session. None of these attributes controls the server's own expiry of the session record.
Quick check
(Session fixation)
A login handler keeps the visitor's existing identifier and only marks that record as authenticated. An attacker has made the victim's browser use the attacker's own known identifier abc. Describe the attack and the fix.
Solution
The victim logs in while holding abc, so the server marks abc as authenticated for the victim's account. The attacker, who already knows abc, now presents it and is treated as the victim. The fix is to issue a fresh random identifier at login, store the authenticated record under it, and delete the old record, so that abc never gains authority. Rotation should happen on every change of privilege.
Quick check
(A logout that does not log out)
A logout route calls only res.clearCookie("sid", cookieOptions) and returns 204. An attacker has a copy of the user's identifier. What happens, and what is the repair?
Solution
The user's browser forgets the cookie, but the server record is still active, so the attacker's copy keeps working until the record expires. The repair is to delete or revoke the record on the server, as sessions.delete(req.cookies.sid) does in the worked example, and to clear the cookie as well. The server-side revocation ends the session; the cookie removal only tidies the browser.
Quick check
(Absolute versus idle expiry)
A session is created at 09:00 with a 30-minute lifetime. Requests arrive at 09:20 and 09:31. State the outcome of each under (a) an absolute expiry at 09:30 and (b) an idle timeout in which every authenticated request sets the expiry to 30 minutes after that request.
Solution
(a) The 09:20 request is authenticated; the 09:31 request is after 09:30, so the session is expired and receives 401. (b) The 09:20 request is authenticated and moves the expiry to 09:50, so the 09:31 request is also authenticated and moves it to 10:01. An idle timeout alone never ends a session that stays in use, so many services combine it with a maximum absolute lifetime.
Quick check
(An over-confident claim)
A teammate says: "Our session cookie is HttpOnly and SameSite=Lax, so XSS and CSRF are impossible." Correct two errors.
Solution
HttpOnly stops script from reading the cookie, but injected script running in the page can still send requests that the browser authenticates with that cookie, so XSS can still act as the user. SameSite=Lax limits when the cookie travels cross-site, yet it does not cover every case, for example requests from another site that counts as same-site, or state changes made through GET. A state-changing cookie-authenticated endpoint still needs a CSRF defense such as a validated token and an origin check, and output must be escaped to prevent XSS.