๐Ÿ“ API

Cookie sessions and CSRF in server-rendered web applications

P
Author
PyLand Team
๐Ÿ“…
Published
18.09.2026
โฑ๏ธ
Reading time
1 min
๐Ÿ‘๏ธ
Views
3
๐ŸŒณ
Level
Advanced

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

  1. Generate a random token and store it in the session.
  2. Put it in a hidden field when rendering the form.
  3. Read the field on POST and compare it with the session value.
  4. Reject a missing or invalid token with 403 before 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_KEY from the environment;
  • use Secure in production and HttpOnly for the cookie;
  • never create or delete data through GET;
  • protect every mutating form, including logout;
  • return 403 before touching the database when token validation fails.

Official references

Your reaction to the article

๐Ÿ’ฌ Comments (0)

๐Ÿ” Sign in to leave a comment
๐Ÿšช Login
๐Ÿ’ญ

No comments yet

Be the first to share your opinion about this article!

๐Ÿ”— Similar

Similar articles

Continue learning with these materials

๐Ÿ“

Secure file uploads: size, type, names, and storaโ€ฆ

Choosing a photo looks simple: the browser sends a file and the server stores it....

๐Ÿ“… 18.09.2026 ๐Ÿ‘๏ธ 1
๐Ÿ“

S3-compatible object storage: buckets, keys, and โ€ฆ

A regular folder works on one computer. After deployment it is unreliable: a container can...

๐Ÿ“… 18.09.2026 ๐Ÿ‘๏ธ 1
๐Ÿ“

REST API Design Principles

Covered topics: Resources and URLs, HTTP methods, Nested resources, Response codes.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 349

Did you like the article?

Subscribe to our updates and be the first to receive new articles. Grow with PyLand!