A cookie session connects browser requests to a user. A signed cookie prevents
undetected modification, but its contents are not necessarily secret. Store only a
user identifier, never a password, API key, or other secret.
Sessions and CSRF are easy to mix up because they solve different problems. A
session identifies the user. CSRF protection proves that a mutating form came
from a page in your application. Login, create, delete, and logout flows need both
layers.
Use HttpOnly, Secure in HTTPS environments, and an appropriate SameSite value.
Keep a stable random SECRET_KEY in the environment and clear the session on logout.
SameSite is defense in depth; mutating HTML forms still need CSRF protection.
Synchronizer token
- Generate a random token and store it in the session.
- Put it in a hidden field when rendering the form.
- Read the field on POST and compare it with the session value.
- Reject a missing or invalid token with
403before changing data.
The token is not the user’s password. It is random proof tied to the current session,
and an attacking website cannot read it from your form.
import secrets
def valid_csrf(expected: str | None, received: str | None) -> bool:
return bool(expected and received) and secrets.compare_digest(expected, received)
Never place CSRF tokens in URLs or logs. GET must not mutate data. Protect logout
and delete POSTs too. In tests, use one client to fetch the form and session cookie,
then submit the token. Also test a missing token and a token from another session.
Pre-release checklist
- load a stable production
SECRET_KEYfrom the environment; - use
Securein production andHttpOnlyfor the cookie; - never create or delete data through GET;
- protect every mutating form, including logout;
- return
403before touching the database when token validation fails.
๐ฌ Comments (0)
No comments yet
Be the first to share your opinion about this article!