Lesson map
Lesson 13 published. Map, example, EX037.
flowchart TD
N0["Learning outcomes"]
N1["13.1 Authentication"]
N2["13.2 Sessions"]
N3["Lab — Lab — tokens and expiry"]
N4["13.3 Lab result"]
N5["13.4 Expiry and logout"]
N6["13.5 Roles"]
N7["13.6 Least privilege"]
N0 --> N1 --> N2 --> N3 --> N4 --> N5 --> N6 --> N7
N7 --> EX["Worked example"]
EX --> Q["Exercise EX037"]
Logical drawing
flowchart LR
N0["Learning outcomes"]
N1["13.1 Authentication"]
N2["13.2 Sessions"]
N3["Lab — Lab — tokens and expiry"]
N4["13.3 Lab result"]
N5["13.4 Expiry and logout"]
N6["13.5 Roles"]
N7["13.6 Least privilege"]
N0 --> N1 --> N2 --> N3 --> N4 --> N5 --> N6 --> N7 --> Q["EX037"]
[Learning outcomes]
|
v
[13.1 Authentication]
|
v
[13.2 Sessions]
|
v
[Lab — Lab — tokens and expiry]
|
v
[13.3 Lab result]
|
v
[13.4 Expiry and logout]
|
v
[13.5 Roles]
|
v
[13.6 Least privilege]
|
v
[Worked example] --> [Exercise EX037]
Learning outcomes
You will (1) implement authentication and sessions securely; (2) generate unpredictable tokens; (3) enforce session expiry; (4) design role-based access control.
13.1 Authentication
Students sign in through the university's single sign-on service, so CampusEats never handles their passwords. Staff accounts require multi-factor authentication. OWASP Top 10:2021 A07 covers identification and authentication failures.
Using single sign-on means password resets, lockouts and account removal for students who leave are handled centrally by the university. CampusEats receives only a signed statement of who the student is, which it verifies before creating a session. Staff accounts carry more power, such as changing prices and issuing refunds, so the extra factor is worth the small inconvenience at each sign-in.
13.2 Sessions
After sign-in, CampusEats creates a session token stored in a cookie. Tokens must be long and random so they cannot be guessed; Python's secrets module provides suitable randomness.
A token built from predictable values, such as a student number and a timestamp, could be guessed by anyone who knew the pattern. The server stores the token with its creation time and last use, and the cookie settings from the earlier chapter on networks keep it out of page scripts and unencrypted connections. A new token is issued at each sign-in.
Lab — Lab — tokens and expiry
"""Create random session tokens and check expiry (synthetic clock)."""
import secrets
tokens = {secrets.token_urlsafe(32): 0, secrets.token_urlsafe(32): 25}
print("token length (chars):", len(next(iter(tokens))))
now, ttl = 40, 30
for i, created in enumerate(tokens.values(), 1):
print(f"token {i}: age {now - created} min -> {'expired' if now - created > ttl else 'valid'}")
print("distinct:", len(tokens) == 2)
Run with python3 lab_session.py. Verified output:
token length (chars): 43
token 1: age 40 min -> expired
token 2: age 15 min -> valid
distinct: True
13.3 Lab result
Each token is 43 characters (32 random bytes encoded), and the two tokens are distinct. With a 30-minute limit and the clock at minute 40, the token created at minute 0 (age 40) is expired and the token created at minute 25 (age 15) is valid.
Lena adds both cases to the tests, along with a token exactly at the limit, since boundary values are where off-by-one mistakes usually hide. The lab uses a fixed clock so that the result is the same on every run. Both checks run in the build.
13.4 Expiry and logout
Sessions expire after 30 minutes of inactivity and are deleted on logout on the server, not just in the browser.
Deleting the session on the server matters because a copied cookie would otherwise keep working after the student pressed logout. Lena tests this by signing out in one browser and replaying the old cookie from another; the server refuses it. Staff sessions use a shorter limit, since a staff account left open on a café till could be misused by anyone passing by.
13.5 Roles
Roles are student, volunteer, staff and admin, each with a defined set of actions from Lena's table in chapter 1. Checks happen on the server for every request.
Lena's tests sign in with each role and try every action, comparing the result with the table. Hiding a button in the page is not a check, because a request can be sent without the button. A volunteer who calls the price-change address directly must be refused by the server, and the refusal is logged so repeated attempts are visible.
13.6 Least privilege
Admin is limited to two people; actions are logged.
Every admin action, such as changing a role or a café's details, is recorded with who did it and when, and the log is reviewed monthly by someone other than the two admins. Most society members work as staff or volunteers and never need admin rights. When an admin leaves the society, the role passes to a named successor the same week, and the departing account is downgraded. The handover is noted in the log.
Access reviews
Each term, the society lists who has staff and admin roles and removes those who have left. Last term two graduates still had admin rights; they were removed. A review takes twenty minutes and closes one of the most common gaps in small teams: forgotten accounts with high privileges.
Logging
Sign-ins, role changes and admin actions are logged with time and user.
Worked example
Lena's test finds that logging out removed the cookie but left the session valid on the server for 30 minutes. A copied cookie would still work. The logout handler now deletes the server-side session, and a test checks it.
Synthetic case. Tokens and sessions are synthetic.
Errors and limits
Expiry times balance security against convenience; very short sessions frustrate users.
Exercises
- EX037 — SSO benefit. Why use university single sign-on?
Show marking criteria
Rubric: 3 = CampusEats never handles passwords; 2 = partial; 1 = vague; 0 = none. - EX038 — Lab expiry. Which token was expired and why?
Show marking criteria
Rubric: 3 = token 1, age 40 > 30; 2 = partial; 1 = vague; 0 = none. - EX039 — Logout fix. What was wrong with logout?
Show marking criteria
Rubric: 3 = server session still valid; now deleted; 2 = partial; 1 = vague; 0 = none.
Synthesis
Use strong identity, random expiring sessions and server-side role checks.
Continue studying — chapter 13 of 40
← Chapter 12 (draft) · Course chapter index · Chapter 14 (draft) →