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:
- Django sets a
csrftokencookie. - Every form that posts back must include the token, which
{% csrf_token %}renders as a hidden input. - For POST, PUT, PATCH and DELETE, the middleware compares the submitted token with the cookie. A missing or wrong token returns 403 Forbidden.
- For HTTPS requests it also checks the
Origin(orReferer) header against the host andCSRF_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_exemptturns protection off for a view. Use it only for endpoints that authenticate without cookies, such as webhooks verified by a signature.SameSite=Laxcookies (Django's default) add a second layer but do not replace tokens.- In DRF,
SessionAuthenticationenforces CSRF; token or JWT authentication in a header does not need it, because browsers do not attach headers automatically.
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