Lesson 03 · 40 minutes
Log in with a session cookie and an API key
- Build a login that issues a random session cookie with safe flags
- Check an API key in constant time
- Name the places where a credential must never appear
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
Your team ships a small API that an internal tool calls with an API key, and staff open a page that needs a login. A reviewer asks three questions: how does the server know who sent a request, what happens when someone logs out, and what is in the logs? Your task is to build the login on your own machine, see the cookie and the key at work, then add a second user and a logout that really ends a session.
Recall
Lesson 1. Who writes the headers of a request, the server or the client?
The client. A client can send any header it wants, so the server must treat every header as untrusted input, including Cookie and X-API-Key.
Lesson 2. A POST to /notes has an empty text. Which status does the server answer, and which kind of code is it?
400 Bad Request. It is a 4xx code, so the client made the mistake. A client error must never be a 5xx.
The idea
Authentication answers "who are you?". The client proves it with a credential. HTTP has no memory, so the credential must come with every request.
| Credential | Used by | How it travels |
|---|---|---|
| Session cookie | Browsers | The server sets Set-Cookie; the browser returns Cookie |
| Bearer token | Apps, mobile | Header Authorization: Bearer <token> (lesson 8 builds one) |
| API key | Programs | A long random secret, in a header such as X-API-Key |
A session works like this: after a good login the server makes a random id, stores id -> user in its own memory and gives the id to the client in a cookie. The id has no meaning by itself; it is a key to data that the server keeps. The id must be unpredictable, so use secrets.token_urlsafe, never random.
Cookie flags:
HttpOnly: page scripts cannot read the cookie, so a script that an attacker runs in your page (XSS, lesson 5) cannot steal it.SameSite=Strict: the browser does not send the cookie on requests that start from another site, which blocks most cross-site request forgery (CSRF: another site makes your browser send a request). An old browser may ignore the flag, so lesson 8 adds a server check.Secure: send only over HTTPS (HTTP inside an encrypted connection). Add it on every real site. This lab uses plain http on localhost, so it is left out.
- Client → Server: POST /login user and password
- Server: compare the password hash
- Server → Session store: save id and user name
- Server → Client: 200 and Set-Cookie sid=...
- Client → Server: GET /me with Cookie sid=...
- Server → Session store: who owns this id?
- Server → Client: 200 and the user name
Worked example
1. Make a key and keep it out of the source
The program reads the key from the environment, a set of named values that the shell gives to every program that it starts. export puts a value into the environment. The Python module secrets makes random values that are safe for security work, and token_urlsafe(32) makes 32 random bytes as URL-safe text. python3 -c "..." runs the short program in the quotes. $(...) runs the command inside and puts its output in its place, so API_KEY gets the random text.
cd ~/krlab/web-apis
export API_KEY=$(python3 -c "import secrets; print(secrets.token_urlsafe(32))")2. Write the server
Create auth.py. Eight things are new:
- A hash is a one-way scramble of a text: you cannot get the password back from it.
hashlib.scryptis a slow hash made for passwords, and the salt is a random value that is mixed in, so equal passwords can give different hashes (this demo uses one salt for all users; the Field notes say what to do instead).os.urandom(16)gives 16 random bytes from the operating system. hmac.compare_digestcompares two values in constant time, so the time to answer does not reveal how many characters were right.Set-Cookieis the response header that gives a cookie to the client.Cookieis the request header that returns it.- The status
401 Unauthorizedmeans "I do not know who you are". - A
Cookieheader looks likea=1; sid=xyz. The code splits it at;and, withpartition("="), cuts each part into a name and a value. Only a cookie named exactlysidcounts, so a cookie namedxsidis ignored. - An f-string such as
f"sid={sid}; ..."puts the value ofsidinto the text. return self.reply(...)sends the answer and leaves the method in one line.DUMMYis a hash of a made-up password. The code hashes the password even when the user does not exist, so that both failures take the same time (see step 5).
The password is in the file only because this is a demo; it is stored as a hash, and lesson 7 removes secrets from code.
auth.py
import hashlib, hmac, json, os, secrets
from http.server import BaseHTTPRequestHandler, HTTPServer
API_KEY = os.environ["API_KEY"] # never written in the source
SALT = os.urandom(16)
def hash_pw(password):
return hashlib.scrypt(password.encode(), salt=SALT, n=2**14, r=8, p=1)
USERS = {"alice": hash_pw("alice-pass")} # demo only: lesson 7 removes secrets from code
DUMMY = hash_pw("not a real password") # used when the user does not exist
SESSIONS = {} # session id -> user name
class Handler(BaseHTTPRequestHandler):
def reply(self, status, obj, cookie=None):
data = json.dumps(obj).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
if cookie:
self.send_header("Set-Cookie", cookie)
self.end_headers()
self.wfile.write(data)
def session_id(self):
for part in self.headers.get("Cookie", "").split(";"):
name, _, value = part.strip().partition("=")
if name == "sid":
return value
return ""
def session_user(self):
return SESSIONS.get(self.session_id())
def do_POST(self):
if self.path != "/login":
return self.reply(404, {"error": "not found"})
try:
size = max(0, int(self.headers.get("Content-Length", 0)))
body = json.loads(self.rfile.read(size))
user, password = body["user"], body["password"]
same = hmac.compare_digest(hash_pw(password), USERS.get(user, DUMMY))
ok = same and user in USERS
except (ValueError, KeyError, TypeError, AttributeError):
return self.reply(400, {"error": "send user and password"})
if not ok:
return self.reply(401, {"error": "wrong user or password"})
sid = secrets.token_urlsafe(32)
SESSIONS[sid] = user
self.reply(200, {"user": user}, f"sid={sid}; HttpOnly; SameSite=Strict; Path=/")
def do_GET(self):
if self.path == "/me":
user = self.session_user()
if user: return self.reply(200, {"user": user})
elif self.path == "/api/data":
key = self.headers.get("X-API-Key", "")
if hmac.compare_digest(key.encode(), API_KEY.encode()):
return self.reply(200, {"data": [1, 2, 3]})
else:
return self.reply(404, {"error": "not found"})
self.reply(401, {"error": "not authenticated"})
HTTPServer(("127.0.0.1", 8300), Handler).serve_forever()3. Start it and log in
Start python3 auth.py in the first terminal. A new terminal starts in your home folder (type cd ~/krlab/web-apis) and does not have the variable API_KEY, and typing the export line again would make a different key. In the first terminal type echo $API_KEY and copy the value. In the second terminal type export API_KEY= and paste the value after the sign. Then log in. The option -c jar.txt (cookie jar) saves the cookies that the server sets into a file.
H=http://127.0.0.1:8300
curl -si -c jar.txt -X POST $H/login -d '{"user":"alice","password":"alice-pass"}'HTTP/1.0 200 OK
Server: BaseHTTP/0.6 Python/3.14.4
Date: Sat, 21 Nov 2026 08:35:13 GMT
Content-Type: application/json
Content-Length: 17
Set-Cookie: sid=gyBjl594IbqCyFsYzTUAJYlLJKCbi0GGASMfMcnRaok; HttpOnly; SameSite=Strict; Path=/
{"user": "alice"}Your id is different, because it is random. The flags are in the header.
4. Use the session
-b jar.txt (send cookies) sends the saved cookies. The second call has no cookie.
curl -s -b jar.txt $H/me
curl -s -w ' [%{http_code}]\n' $H/me{"user": "alice"}
{"error": "not authenticated"} [401]5. Send a wrong password
curl -s -w ' [%{http_code}]\n' -X POST $H/login -d '{"user":"alice","password":"nope"}'
curl -s -w ' [%{http_code}]\n' -X POST $H/login -d '{"user":"mallory","password":"x"}'{"error": "wrong user or password"} [401]
{"error": "wrong user or password"} [401]Both failures give the same answer. If the message said "no such user", an attacker could list the valid names. The time must be equal too: the code hashes the password in both cases (DUMMY), so the unknown user is not faster. Without that, alice with a wrong password takes tens of milliseconds (the slow hash) and mallory about 1 ms, and a clock reveals the valid names.
6. Call with the API key
curl -s -H "X-API-Key: $API_KEY" $H/api/data
curl -s -w ' [%{http_code}]\n' -H "X-API-Key: wrong" $H/api/data{"data": [1, 2, 3]}
{"error": "not authenticated"} [401]7. Put the key in the URL and read the log
This is the mistake to avoid. The query string is the part of a URL after the ?. Send the key there, then look at the first terminal.
curl -s "$H/api/data?key=$API_KEY"127.0.0.1 - - [21/Nov/2026 08:35:13] "GET /api/data?key=hY1NQU15qy8UfBN-CfS0pV-0uPSZEk_5hxFqbzFzWQw HTTP/1.1" 404 -The server did not even accept the key from the URL, yet the log now holds it. A URL also goes into browser history, proxy logs and the Referer header (a header that tells a site which page the visitor came from, with that page's whole URL). Stop the server, and treat that key as lost: make a new one.
Your turn
The reviewer wants a second user and a real logout. Change your own auth.py. There are no steps here. Hint: self.session_id() gives the id from the cookie, and dict.pop(key, None) removes a key and returns its value, or None when the key is missing.
- Add the user
bobwith the passwordbob-pass. - Add
POST /logout. With a valid session cookie it deletes that session on the server and answers 200. With no cookie, or with a cookie that is not a live session, it answers 401. - Restart the server. Log in as bob and save the cookie in a file. Call
/mewith that cookie, then call/logoutwith it, then call/mewith the same cookie file again. Last, try to log in as bob with the passwordalice-pass.
Last, call /logout a second time with the same cookie. A cookie that the server no longer knows must get the same answer as no cookie.
Check yourself
Why is the session id random and long, while the server stores the user name itself?
The id is the only secret in the cookie. If it were guessable, an attacker could build a valid cookie for another user. The user name is stored on the server, where the client cannot change it.
What does HttpOnly protect against, and what does it not protect against?
It stops page scripts from reading the cookie, so an XSS flaw cannot send the cookie away. It does not stop the browser from sending the cookie, so an attacker's script can still make requests as the user.
Name three places where a credential must never appear.
In a URL (logs, history, Referer), in a log line, and in source code (version control keeps it for ever and many people can read it). Use a header or a cookie and keep the value in an environment variable or a secret store.
Field notes
- Make a new session id at login and delete the old session at logout and at password change. Reusing the id from before login enables session fixation (an attacker plants a known id, waits for the user to log in, and then holds a logged-in id). This is OWASP Top 10 (2021 edition) "Identification and Authentication Failures".
- Store passwords with a slow hash made for the job (scrypt, Argon2 or bcrypt) and a random salt for each user. This demo uses one salt for brevity; do not copy that. The setting
n=2**14, r=8, p=1keeps the demo fast. OWASP advises Argon2id first, or scrypt with at leastn=2**17(Python also needs a largermaxmemfor that); check the current advice. - Many real systems do not store passwords at all. They accept a signed token from an identity provider (OAuth 2.0 and OpenID Connect, with the authorisation code flow and PKCE for a browser or app). Lesson 8 shows how such a token is checked.
- Give sessions an expiry and an idle timeout, and clear expired entries. The dictionary here grows without limit.
- Store only a hash of an API key in your database, as you would a password, and show the full key once, at creation. Give each key a name and a scope, so you can revoke one without breaking all.
- A login endpoint needs a rate limit (lesson 7). The OWASP API Security Top 10 calls this area "Broken Authentication".