CSRF middleware checks unsafe requests against a token and origin policy to reduce unauthorized cross-site actions in a browser session.
Django CSRF checks: require the token without confusing it with identity
Operation contract
The local review view obtains a CSRF cookie on GET. A test client with CSRF enforcement enabled receives a forbidden result for a POST without the matching token and accepts a POST carrying it. The fixture checks both paths; the default test client’s relaxed behavior would not establish this protection.
Failure and ownership boundary
The token does not prove user identity, record ownership or safe input. Real HTTPS deployment also needs the appropriate origin, cookie, proxy and session configuration. The fixture uses a local test-only secret and testserver host, makes no network listener and stores no user session. Django forms: ASCII wire fields and cleaned domain values and Flask JSON API: reject unknown fields, booleans and oversized bodies remain necessary after an origin check succeeds.
Tested environment
Dependency check: this program was executed on CPython 3.14.6 with Django==5.2.17. Install these versions in a separate virtual environment. The download includes the recorded environment snapshot; no third-party package is part of the website runtime.
Working program
from django.conf import settings
settings.configure(SECRET_KEY="owned-local-csrf-fixture", ROOT_URLCONF=__name__,
ALLOWED_HOSTS=["testserver"],
MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"], INSTALLED_APPS=[])
import django
django.setup()
from django.http import HttpResponse
from django.middleware.csrf import get_token
from django.urls import path
from django.test import Client
def review(request):
get_token(request)
return HttpResponse("local review received")
urlpatterns = [path("review/", review)]
client = Client(enforce_csrf_checks=True)
client.get("/review/")
token = client.cookies["csrftoken"].value
print("without token:", client.post("/review/", {}).status_code)
print("with token:", client.post("/review/", {}, HTTP_X_CSRFTOKEN=token).status_code)Output
without token: 403
with token: 200Costs and limits
This test exercises in-process middleware dispatch. It does not measure network latency or verify a production reverse proxy. Token checks are only one part of a request’s total parsing, database and authorization cost.
Common Mistakes
- Enable CSRF enforcement in the test that claims to check it.
- A valid token is not permission to change a receipt.
Connected lessons
Django forms: ASCII wire fields and cleaned domain values, Django templates: escape untrusted text at HTML output, Flask JSON API: reject unknown fields, booleans and oversized bodies.
