# Cookies and Sessions: How a Website Remembers You

You log in to a website. You click to another page. You are still logged in.

That feels normal, but it is a little strange. The web was not built to remember you.

---

## The Problem: The Web Has No Memory

The Hypertext Transfer Protocol (HTTP) is the language browsers and web servers use to talk. RFC (Request for Comments) 9110, the HTTP specification, describes it as a stateless protocol, meaning each request message can be understood in isolation.

Plain version: every request arrives as if the server has never seen you before.

So after you log in, the server needs a way to connect your next request to your login. That is the job of a session.

---

## Cookies and Sessions Are Two Different Things

**A cookie** is a small piece of data a server asks your browser to store and send back on later requests.

**A session** is the server's record of who you are and what you are doing during a visit.

Think of a coat check. You hand over your coat and get a numbered ticket. The ticket is the cookie. Your coat is the session.

Notice what the attendant does not do. They do not check your face. Whoever holds the ticket gets the coat.

That is the security lesson of this whole article.

---

## What It Looks Like on the Wire

After a successful login, the server's response may include a header like this:

```http
Set-Cookie: sid=9f2c4e1a7b8d3c05a6e2f1b47d90c8ab; Path=/; HttpOnly; SameSite=Lax; Max-Age=600
```

Your browser stores it. On later requests to that site, the browser sends this back:

```http
Cookie: sid=9f2c4e1a7b8d3c05a6e2f1b47d90c8ab
```

Two details matter here.

The `sid` value is only a reference. The server uses it to look up your session.

The browser sends back only the name and value. Attributes like `HttpOnly` and `SameSite` are instructions for the browser, and the server does not see them again.

---

## What Makes a Good Session ID

The OWASP (Open Worldwide Application Security Project) Session Management Cheat Sheet sets the ground rules.

- **Unpredictable.** Generated by a cryptographically secure random number generator, with at least 64 bits of entropy (randomness).
- **Meaningless.** It should contain no username, email address, or other personal data. That information stays on the server.

A good session ID is a long random reference number, not a label like `user=patrick`.

Anything stored in the browser is something the user can change. That is why a server should never trust a cookie that says `role=admin`.

---

## The Cookie Attributes That Matter

| Attribute | What it does | What it does not do |
| --- | --- | --- |
| `Secure` | Tells the browser to send the cookie only over HTTPS (HTTP Secure) | Does not encrypt anything by itself |
| `HttpOnly` | Blocks JavaScript from reading the cookie | Does not stop cross-site scripting (XSS) |
| `SameSite` | Limits sending the cookie on requests that start from a different site | Is not a complete defense against cross-site request forgery (CSRF) |
| `Max-Age` / `Expires` | Tells the browser when to discard the cookie | Does not control how long the server accepts the session |
| `Domain` / `Path` | Controls which hosts and paths receive the cookie | A broad `Domain` can expose it to sibling subdomains |

Two terms in that table deserve a quick definition.

XSS is an attack where a malicious script runs inside a page the user trusts. CSRF is an attack that tricks a logged-in user's browser into sending a request the user did not intend.

OWASP advises setting `SameSite` explicitly (`Strict` preferred, or `Lax`) instead of relying on browser defaults. It also recommends the `__Host-` cookie name prefix for session IDs, which requires `Secure`, no `Domain`, and `Path=/`.

---

## Sessions Need an Ending

A session that never ends is a standing invitation.

- **Timeouts.** OWASP says every session needs an idle timeout and an absolute timeout, enforced on the server. A client-side timer alone can be bypassed.
- **A new ID after login.** The application should issue a fresh session ID after login and after privilege changes. This blocks session fixation, an attack where someone gets you to use a session ID they already know.
- **A real logout.** Logging out must end the session on the server. Deleting the cookie in the browser does not invalidate a stolen copy of the ID.

---

## How This Connects to Earlier Articles

In [Authentication vs. Authorization: Why the Difference Matters](ADD-HASHNODE-URL), login was the authentication step. The session is how the system remembers that result and applies authorization to every request after it.

In [What Multi-Factor Authentication Actually Protects You From](ADD-HASHNODE-URL), multi-factor authentication (MFA) strengthened the login step. The session that follows is a separate thing worth protecting.

A valid session ID may be enough to act as that user until the session ends. That is why timeouts, `HttpOnly`, and server-side logout matter even with strong passwords. See [Passwords Aren't Dead, but They Shouldn't Be Working Alone](ADD-HASHNODE-URL).

---

## Common Misconceptions

### "A cookie is a program or a virus."

A cookie is text. It cannot run anything by itself.

### "The cookie is the login."

The cookie is a reference to a session. The login happened earlier, on the server.

### "HttpOnly prevents XSS."

It limits one outcome of XSS, which is a script reading the cookie. The script can still do other things inside the page.

### "Secure encrypts the cookie."

It only tells the browser to send the cookie over HTTPS. The encryption comes from the connection.

### "Clearing cookies is a secure logout."

Clearing removes your copy. If the server never ends the session, a copied ID may keep working.

---

## Practical Exercise: Watch a Session Work

This lab runs on your own machine or lab VM. The server listens on `127.0.0.1` only, so nothing outside your computer can reach it.

It is a teaching toy, not real session code. Real applications should use the session handling built into a mature framework.

The lab omits `Secure` because localhost has no HTTPS. A real site must set it.

**Step 1: Save this as** `cookie_lab.py`

Ubuntu Server normally includes Python 3. Check with `python3 --version`.

```python
from http.server import BaseHTTPRequestHandler, HTTPServer
import secrets

SESSIONS = {}


def get_sid(headers):
    for part in headers.get("Cookie", "").split(";"):
        name, _, value = part.strip().partition("=")
        if name == "sid":
            return value
    return ""


class Handler(BaseHTTPRequestHandler):
    def reply(self, code, body, extra=None):
        self.send_response(code)
        for key, value in (extra or {}).items():
            self.send_header(key, value)
        self.end_headers()
        self.wfile.write(body.encode() + b"\n")

    def do_GET(self):
        if self.path == "/login":
            sid = secrets.token_hex(16)
            SESSIONS[sid] = "lab-user"
            cookie = f"sid={sid}; Path=/; HttpOnly; SameSite=Lax; Max-Age=600"
            self.reply(200, "Logged in", {"Set-Cookie": cookie})
        elif self.path == "/whoami":
            user = SESSIONS.get(get_sid(self.headers))
            if user:
                self.reply(200, f"You are {user}")
            else:
                self.reply(401, "No valid session")
        elif self.path == "/logout":
            SESSIONS.pop(get_sid(self.headers), None)
            self.reply(200, "Session ended on the server")
        else:
            self.reply(404, "Not found")


HTTPServer(("127.0.0.1", 8080), Handler).serve_forever()
```

**Step 2: Start it in one terminal**

```bash
python3 cookie_lab.py
```

**Step 3: In a second terminal, log in and look at the headers**

```bash
curl -si -c jar.txt http://127.0.0.1:8080/login
```

You should see a `Set-Cookie` header with a 32-character `sid` and the attributes from the script.

**Step 4: Use the session, then try without it**

```bash
curl -s -b jar.txt http://127.0.0.1:8080/whoami
curl -si http://127.0.0.1:8080/whoami | head -1
```

Expected results:

```text
You are lab-user
HTTP/1.0 401 Unauthorized
```

**Step 5: Copy the session ID, end the session, and replay the copy**

```bash
SID=$(awk '$6=="sid"{print $7}' jar.txt)
curl -s -H "Cookie: sid=$SID" http://127.0.0.1:8080/whoami
curl -s -b jar.txt http://127.0.0.1:8080/logout
curl -s -H "Cookie: sid=$SID" http://127.0.0.1:8080/whoami
```

Expected results:

```text
You are lab-user
Session ended on the server
No valid session
```

**Questions to answer**

1. What did the server actually send you at login?
2. Why did `whoami` fail without the cookie?
3. Why did the copied ID stop working after logout?
4. What would someone need in order to impersonate you in this lab?

Stop the server with Ctrl+C and delete `jar.txt` when you are done.

---

## Key Takeaway

A cookie is a reference. A session is the server's record behind it. The web needs both because HTTP does not remember you.

Whoever holds a valid session ID may be treated as you, so protect the ID, limit its lifetime, and end sessions on the server.

---

## Verified References

- IETF RFC 9110, HTTP Semantics (statelessness, Section 3.3). <https://www.rfc-editor.org/rfc/rfc9110>
- IETF RFC 6265, HTTP State Management Mechanism. <https://www.rfc-editor.org/rfc/rfc6265>
- IETF Internet-Draft, Cookies: HTTP State Management Mechanism (draft-ietf-httpbis-rfc6265bis, the update to RFC 6265, in the RFC Editor queue at the time of writing). <https://datatracker.ietf.org/doc/draft-ietf-httpbis-rfc6265bis/>
- OWASP Session Management Cheat Sheet. <https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html>
- MDN Web Docs, Secure cookie configuration. <https://developer.mozilla.org/en-US/docs/Web/Security/Practical_implementation_guides/Cookies>

---
