Lesson 31 of 59Identity and access
Cookie Sessions, CSRF and Logout That Works
Run server-side sessions in Redis with the right cookie flags, defend against CSRF properly, and make logout and revocation actually work.
Authentication and JWTs ended by naming three follow-ups, and this unit is those three plus multi-tenancy. A customer emails support: their laptop was stolen, they changed their password from their phone, and the thief is still logged in an hour later. Your API issues 30-day JWTs, so there is nothing to delete. Or the security team runs a scan and flags your SPA for keeping tokens in localStorage. Both tickets lead to the same place: browser sessions held in cookies, with state on the server. The authentication lesson compared sessions and tokens in one table. This lesson is the version you need to run sessions in production: the cookie flags, the session store, CSRF, revocation, and how a modern SPA fits in.
A cookie, attribute by attribute
A cookie is a name and value that the server sets with a Set-Cookie header. The browser stores it and sends it back in a Cookie header on matching requests. The attributes decide which requests match and who can read it.
| Attribute | What it does | What you want for a session |
|---|---|---|
HttpOnly | JavaScript cannot read it through document.cookie | Always |
Secure | Only sent over HTTPS | Always |
SameSite=Lax | Not sent on cross-site subrequests (forms posted from other sites, fetch, images). Sent on top-level GET navigations | The default choice |
SameSite=Strict | Never sent on any cross-site request, even clicking a link to you | Banking-style apps, at the cost of looking logged out after following a link |
SameSite=None | Sent everywhere. Requires Secure | Only for real cross-site embeds |
Path | Only sent for URLs under this path | / for sessions, narrower for a refresh cookie |
Domain | Sent to this domain and all its subdomains | Leave it out, so the cookie is host-only |
Max-Age / Expires | Persistent cookie that survives a browser restart. Without them it is a session cookie | Your choice; browsers cap lifetimes at about 400 days |
Two of these deserve more attention. Setting Domain=example.com sounds harmless, but it sends the session to blog.example.com, status.example.com and whatever a marketing agency hosts on a subdomain next year. Any of them can then read or overwrite it. The __Host- prefix locks this down: a cookie named __Host-sid is only accepted if it has Secure, Path=/ and no Domain. The browser enforces it, so a subdomain cannot plant a cookie with that name.
"Same-site" is also not "same-origin". An origin is scheme, host and port. A site is the scheme plus the registrable domain, so https://app.example.com and https://evil.example.com are different origins but the same site. SameSite does nothing against an attacker who controls a sibling subdomain.
In FastAPI you set cookies on the response:
from fastapi import Response
COOKIE = "__Host-sid"
def set_session_cookie(response: Response, session_id: str) -> None:
response.set_cookie(
COOKIE, session_id,
httponly=True, secure=True, samesite="lax", path="/",
)Starlette defaults samesite to "lax" but secure and httponly to False, so pass them every time. Leaving out max_age makes it a browser-session cookie; the server-side record decides when the session really ends.
Match each threat to the cookie setting that addresses it.
Server-side sessions in Redis
A server-side session is two things: a random, unguessable id in the cookie, and a record on the server keyed by that id. The id carries no meaning. All the facts (who the user is, when they logged in) live on the server, where you can change or delete them.
Generate the id with secrets.token_urlsafe(32): 32 random bytes, 256 bits, 43 characters. Never use uuid4 built from a weak source, an incrementing number, or anything derived from the user id. Then store a hash of the id as the Redis key, not the id itself. If someone gets a copy of Redis or a key dump in a log, they get hashes, which cannot be turned back into working cookies. SHA-256 is fine here: unlike passwords, the input is already 256 random bits, so there is nothing to brute force.
A session record usually holds the user id, when it was created, when it was last used, and the IP address and user agent at login. The last two are not for blocking (IPs change on mobile networks all the time). They are for the "active sessions" page you will build later.
Sessions need two clocks:
- Idle (sliding) timeout: the session ends after, say, 30 minutes with no requests. Each request pushes the deadline forward. In Redis this is just the key's TTL, refreshed with
EXPIREon every request. - Absolute timeout: the session ends 12 hours (or 30 days, for a consumer app with "remember me") after login, however active it is. This bounds how long a stolen cookie works. Store
createdin the record and check it.
Press Run (⌘ Enter) to see what happens.The busy user never hits the idle timeout, but the absolute timeout still logs them out after 12 hours. Here is the same design as a FastAPI dependency with redis.asyncio:
import hashlib
import json
import secrets
import time
from typing import Annotated
from fastapi import Cookie, Depends, HTTPException, Request, status
from redis.asyncio import Redis
from app.auth.cookies import COOKIE
from app.core.redis import redis # one shared client, created in lifespan
IDLE_TIMEOUT = 30 * 60
ABSOLUTE_TIMEOUT = 12 * 3600
def _key(session_id: str) -> str:
return "session:" + hashlib.sha256(session_id.encode()).hexdigest()
async def create_session(user_id: int, request: Request) -> str:
session_id = secrets.token_urlsafe(32)
record = {
"user_id": user_id,
"created": int(time.time()),
"ip": request.client.host if request.client else "",
"ua": request.headers.get("user-agent", "")[:200],
}
await redis.set(_key(session_id), json.dumps(record), ex=IDLE_TIMEOUT)
await redis.sadd(f"user_sessions:{user_id}", _key(session_id))
return session_id
async def current_session(sid: Annotated[str | None, Cookie(alias=COOKIE)] = None) -> dict:
if sid is None:
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Not logged in")
key = _key(sid)
raw = await redis.get(key)
if raw is None:
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Session expired")
record = json.loads(raw)
if time.time() - record["created"] > ABSOLUTE_TIMEOUT:
await redis.delete(key)
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Session expired")
await redis.expire(key, IDLE_TIMEOUT) # slide the idle deadline
return record | {"key": key}
Session = Annotated[dict, Depends(current_session)]The user_sessions:{user_id} set is an index from a user to all their sessions. You will need it for "log out everywhere". Because it is a set of keys that expire on their own, clean out stale members when you read it.
Using create and lookup from the runnable block, what does this print?
sid = create(1, now=0) print(lookup(sid, 29 * 60), lookup(sid, 58 * 60), lookup(sid, 90 * 60))
Session fixation: rotate the id
Session fixation is an attack where the attacker gets a victim to use a session id the attacker already knows. For example, the app creates an anonymous session for the shopping basket, the attacker plants their own id in the victim's browser, the victim logs in, and the app upgrades that same session to "logged in as the victim". The attacker's copy of the id is now a logged-in session.
The fix is simple and non-negotiable: issue a brand-new session id on login, and delete the old one. Do the same on any privilege change: a user who steps up to an admin mode, confirms their password for a sensitive action, or switches organisation. Copy over any anonymous data you want to keep (the basket), then delete the old record.
Order what a correct login endpoint does.
- Tap the steps below in the right order.
SessionMiddleware is a signed cookie, not a store
FastAPI tutorials often add Starlette's SessionMiddleware and call request.session "the session". It is useful, but it is not server-side storage. It serialises the whole dict to JSON, base64-encodes it, signs it with itsdangerous, and puts all of it in the cookie. Here is a real cookie it produced, and what decoding the first part gives:
app.add_middleware(SessionMiddleware, secret_key=settings.session_secret, https_only=True)
# Set-Cookie: session=eyJ1c2VyX2lkIjogNywgInJvbGUiOiAiYWRtaW4ifQ==.atpnrA.FjfsQXI2...
base64.b64decode("eyJ1c2VyX2lkIjogNywgInJvbGUiOiAiYWRtaW4ifQ==")
# b'{"user_id": 7, "role": "admin"}'The signature stops tampering, but there is no secrecy (anyone can read it) and no server state. That has three consequences. First, cookies are capped at roughly 4 KB, so the session must stay small. Second, request.session.clear() on logout only replaces the cookie in that browser. If an attacker copied the old cookie, it keeps working until its max_age (14 days by default) runs out. Testing this against a real app shows exactly that: the copied cookie still returns the old session after logout. Third, "log out everywhere" is impossible without adding server state.
SessionMiddleware is a good fit for short-lived, low-value state, such as the OAuth state and nonce during a login redirect (you will use it for exactly that in the next lesson). For the logged-in session, use a server-side store.
CSRF: why cookies make it possible
Cookies are ambient credentials: the browser attaches them to every matching request, whoever started it. Cross-site request forgery (CSRF) abuses that. A page on another site makes the victim's browser send a request to your API, and the browser helpfully adds the session cookie.
The victim logs in normally. The browser now holds your session cookie.
SameSite=Lax blocks this exact attack, because a cross-site form POST is a subrequest that does not get the cookie. That is why Lax is a big improvement. It does not remove the need for a defence, though:
- Top-level GET navigations still send Lax cookies. If
GET /account/delete?confirm=1deletes anything, a link does the attack. Never change state on GET. - Same-site attackers are not cross-site. A compromised
forum.example.com, or a user-content subdomain, is the same site asapp.example.com. SameSite does not apply. - Defaults differ between browsers. Chrome treats a cookie with no
SameSiteattribute as Lax, but with a two-minute window after it is set where cross-site top-level POSTs still carry it. Other browsers do not apply Lax by default at all. Set the attribute explicitly. - Older or unusual clients may not enforce SameSite the way you expect.
CSRF defences that work
FastAPI has no built-in CSRF protection, so it is your job. Use one primary defence plus SameSite.
Fetch metadata. Modern browsers send Sec-Fetch-Site on every request: same-origin, same-site, cross-site or none (typed in the address bar). Rejecting unsafe methods unless the value is same-origin stops cross-site and sibling-subdomain forgery, with no tokens and no frontend changes. Fall back to checking Origin against an allow-list when the header is missing.
from fastapi import Request, Response
SAFE_METHODS = {"GET", "HEAD", "OPTIONS"}
TRUSTED_ORIGINS = {"https://app.example.com"}
@app.middleware("http")
async def reject_cross_site(request: Request, call_next):
if request.method not in SAFE_METHODS:
site = request.headers.get("sec-fetch-site")
origin = request.headers.get("origin")
if site is not None:
allowed = site in {"same-origin", "none"}
else:
allowed = origin is None or origin in TRUSTED_ORIGINS
if not allowed:
return Response("Cross-site request blocked", status_code=403)
return await call_next(request)origin is None lets non-browser clients (curl, other services) through. That is fine: they do not carry a victim's cookies. If your frontend lives on a different origin from the API, add same-site and check Origin for that case.
Synchronizer token. The server puts a random token in the session and in the page; every unsafe request must echo it in a header or form field. The attacker cannot read your page, so they cannot learn it. The signed double-submit variant avoids storing the token: the token is an HMAC of the session id, so the server can verify it with only its secret.
Press Run (⌘ Enter) to see what happens.The last line is why the token must be bound to the session. A "naive" double-submit cookie (a random value in a cookie, compared with the same value in a header) can be beaten by an attacker who can write cookies from a sibling subdomain.
Logout that works
With server-side sessions, logout is a delete. Do it properly:
- Log out: delete the session record, remove it from the user's set, and expire the cookie with
response.delete_cookie(COOKIE, path="/", secure=True, httponly=True, samesite="lax"). The attributes must match how it was set, or the browser keeps the old one. - Log out everywhere: read
user_sessions:{user_id}and delete every key in it. - Password change or reset: delete all the user's other sessions. This is the fix for the stolen-laptop ticket, and many apps forget it.
- Account disabled: delete all sessions, so the change takes effect on the next request, not next month.
- An "active sessions" page: list the records in the user's set with created time, last seen, and a friendly device name parsed from the user agent, each with a "revoke" button. Users notice strange logins faster than your alerting does.
@router.post("/logout-everywhere")
async def logout_everywhere(session: Session, response: Response):
keys = await redis.smembers(f"user_sessions:{session['user_id']}")
if keys:
await redis.delete(*keys)
await redis.delete(f"user_sessions:{session['user_id']}")
response.delete_cookie(COOKIE, path="/", secure=True, httponly=True, samesite="lax")
return {"ok": True}Redis is now part of your authentication path. If it is down, nobody is logged in. Run it with persistence and a replica, and decide in advance whether a Redis outage means "fail closed" (everyone sees 401s) or a read-only degraded mode. For sessions, failing closed is the right answer.
SPAs, CORS and the backend-for-frontend
Cookie sessions work for SPAs too. The cleanest setup serves the SPA and the API from the same origin (app.example.com for pages, app.example.com/api for the API through a reverse proxy). Then there is no CORS at all, cookies are first-party, and SameSite=Lax plus a Sec-Fetch-Site check is enough.
If the API is on another origin, the browser needs CORS to allow credentials. As the middleware lesson showed, allow_credentials=True cannot be combined with allow_origins=["*"]; list exact origins. On the frontend, fetch needs credentials: "include". If the two are different sites (not just different subdomains), the cookie needs SameSite=None; Secure, and browsers that block third-party cookies may drop it anyway. That is a strong reason to keep the API on the same site.
When the SPA logs in with an external identity provider, the pattern the IETF's guidance for browser-based apps rates most secure is the backend-for-frontend (BFF). A small server-side component does the OAuth flow, keeps the access and refresh tokens, and gives the browser only an HttpOnly session cookie. The SPA calls the BFF, which attaches the access token and forwards to the APIs.
The SPA sends requests with an HttpOnly session cookie. No JavaScript ever sees a token.
An XSS bug in the SPA can still make requests through the BFF while the user has the page open. What it cannot do is steal a token and use it from the attacker's machine for days. That difference is the whole argument.
- host-only cookie
- A cookie set without
Domain, sent only to the exact host that set it, not to subdomains. - __Host- prefix
- A cookie name prefix the browser only accepts with
Secure,Path=/and noDomain. - SameSite
- A cookie attribute that controls whether the cookie is sent on requests started by other sites.
- session fixation
- An attack that makes a victim log in on a session id the attacker knows. Fixed by rotating the id at login.
- CSRF
- Cross-site request forgery: another site makes the victim's browser send an authenticated request.
- Sec-Fetch-Site
- A browser request header saying whether the request came from the same origin, same site, another site, or the user.
- backend-for-frontend (BFF)
- A server-side component that holds OAuth tokens for a browser app and gives the browser only a session cookie.