← Back to Django, page 1

django-0013 · Easy fresher

What is CSRF, and how does Django protect against it?

CSRF (cross-site request forgery) tricks a logged-in user's browser into sending an unwanted request, using the cookies the browser attaches automatically. Django's CsrfViewMiddleware requires a secret token on unsafe requests (POST, PUT, PATCH, DELETE); forms include it with {% csrf_token %} and JavaScript sends it in the X-CSRFToken header. Requests without a matching token get 403.

Full answer

Imagine a student is logged in to the college portal. They open another site that contains a hidden form posting to portal.example/fees/transfer/. The browser sends the portal's session cookie with that request automatically, so without protection the portal would think the student made it. That is cross-site request forgery.

Django's defence is django.middleware.csrf.CsrfViewMiddleware, enabled by default:

  1. Django sets a csrftoken cookie.
  2. Every form that posts back must include the token, which {% csrf_token %} renders as a hidden input.
  3. For POST, PUT, PATCH and DELETE, the middleware compares the submitted token with the cookie. A missing or wrong token returns 403 Forbidden.
  4. For HTTPS requests it also checks the Origin (or Referer) header against the host and CSRF_TRUSTED_ORIGINS.

The attacker's site cannot read the cookie or the page because of the browser's same-origin policy, so it cannot supply the right token.

For JavaScript calls, read the token (from the cookie or a rendered value) and send it in the X-CSRFToken header.

Rules worth knowing:

  • GET requests must not change data. CSRF checks skip safe methods.
  • @csrf_exempt turns protection off for a view. Use it only for endpoints that authenticate without cookies, such as webhooks verified by a signature.
  • SameSite=Lax cookies (Django's default) add a second layer but do not replace tokens.
  • In DRF, SessionAuthentication enforces CSRF; token or JWT authentication in a header does not need it, because browsers do not attach headers automatically.
python
import sys
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django.http import HttpResponse
from django.middleware.csrf import get_token
from django.test import Client
from django.urls import path
from django.views.decorators.csrf import ensure_csrf_cookie


@ensure_csrf_cookie
def form_page(request):
    return HttpResponse(f'<input name="csrfmiddlewaretoken" value="{get_token(request)}">')


def pay_fee(request):
    return HttpResponse("payment recorded")


urlpatterns = [path("form/", form_page), path("pay/", pay_fee)]
settings.ROOT_URLCONF = __name__
settings.MIDDLEWARE = ["django.middleware.csrf.CsrfViewMiddleware"]

client = Client(enforce_csrf_checks=True)
print("POST without token:", client.post("/pay/").status_code)

client.get("/form/")
token = client.cookies["csrftoken"].value
print("POST with token:", client.post("/pay/", {"csrfmiddlewaretoken": token}).status_code)
print("Header token:", client.post("/pay/", HTTP_X_CSRFTOKEN=token).status_code)

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. The test Client normally skips CSRF checks; enforce_csrf_checks=True turns them on. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): POST without token: 403 POST with token: 200 Header token: 200

Key points

  • CSRF abuses cookies that browsers send automatically
  • CsrfViewMiddleware checks a token on unsafe methods
  • Use {% csrf_token %} in forms and X-CSRFToken in JavaScript
  • Never change data on GET
  • csrf_exempt only for non-cookie-authenticated endpoints

Common mistakes

  • Adding @csrf_exempt to make a form 'work' instead of including the token
  • Changing data in a GET view
  • Thinking CSRF protects against XSS; an XSS bug can read the token
  • Assuming token-in-header APIs need CSRF tokens too

Follow-ups

  • Why does a JWT sent in the Authorization header not need CSRF protection?
  • What does SameSite=Lax change?
  • When is csrf_exempt acceptable?

Tips

  • Explain the attack with a concrete scenario before the defence
  • Mention both the form field and the header
  • Link CSRF to cookie-based auth specifically