← Back to Chapters

CSRF Protection in Django

?️ CSRF Protection in Django

? Quick Overview

Cross-Site Request Forgery (CSRF) is a security vulnerability where an attacker tricks a user into performing unwanted actions on a trusted website. Django provides built-in CSRF protection to safeguard applications from such attacks.

? Key Concepts

  • CSRF relies on authenticated browser sessions
  • Django uses per-request unique tokens
  • Tokens must be sent with POST requests
  • Invalid or missing tokens result in request rejection

? Syntax & Theory

Django verifies CSRF tokens for unsafe HTTP methods like POST, PUT, and DELETE. Tokens are automatically added to forms and validated on submission.

? Code Examples

? View Code Example
// Enable CSRF middleware in Django
MIDDLEWARE = [
'django.middleware.csrf.CsrfViewMiddleware',
]
? View Code Example
// Adding CSRF token to a Django form
<form method="post">
{% csrf_token %}
<button type="submit">Submit</button>
</form>
? View Code Example
// Sending CSRF token via AJAX request
var csrftoken = $('[name="csrfmiddlewaretoken"]').val();
$.ajax({
type: "POST",
url: "/some-url/",
headers: {'X-CSRFToken': csrftoken}
});

? Live Output / Explanation

If a request is sent without a valid CSRF token, Django responds with a 403 Forbidden error, blocking malicious activity.

? View Code Example
// Custom CSRF failure handler
from django.http import HttpResponseForbidden

def csrf_failure(request, reason=""):
return HttpResponseForbidden("CSRF token missing or invalid")

? Interactive / Visual Concept

Think of the CSRF token as a secret handshake between the browser and server. If the handshake fails, access is denied.

? Handshake Simulator

Server expects: LOADING...
 

? Use Cases

  • Protecting user account actions
  • Securing payment and form submissions
  • Preventing unauthorized data modification

✅ Tips & Best Practices

  • Always include {% csrf_token %} in forms
  • Use HTTPS to protect token integrity
  • Avoid unnecessary CSRF exemptions

? Try It Yourself

  • Submit a form without CSRF token and observe the error
  • Add CSRF headers to AJAX requests
  • Test @csrf_exempt cautiously