← Back to Chapters

CSRF Protection

?️ CSRF Protection

? Quick Overview

Cross-Site Request Forgery (CSRF) is a security attack where a malicious user performs unauthorized actions on behalf of a logged-in user. Django provides built-in CSRF protection to prevent such attacks.

? Key Concepts

  • CSRF tokens uniquely identify trusted requests
  • Tokens are validated against user sessions
  • Protection applies to all unsafe HTTP methods

? Syntax & Theory

  • Django injects a hidden CSRF token in forms
  • Token must be sent back with POST requests
  • Invalid or missing tokens result in 403 errors

? Code Examples

? View Code Example
// Django template with CSRF protection
{% extends "base.html" %}
{% block content %}
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
{% endblock %}
? View Code Example
// AJAX request including CSRF token
$.ajax({
type: "POST",
url: "/submit-form/",
headers: {
'X-CSRFToken': '{{ csrf_token }}'
},
success: function() {
alert("Form submitted successfully!");
}
});
? View Code Example
// Disabling CSRF protection using decorator
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse

@csrf_exempt
def my_view(request):
return JsonResponse({"message": "Success"})

? Live Output / Explanation

When CSRF protection is enabled, Django validates the token before processing requests. Missing or incorrect tokens trigger security errors.

? Interactive Example

Simulate a sensitive action (like a bank transfer). Toggle the checkbox to decide if you want to include the valid security token or not.

? Mock Bank Transfer Session Active
Waiting for action...

? Use Cases

  • Protecting user profile updates
  • Securing financial transactions
  • Validating form submissions

✅ Tips & Best Practices

  • Always include CSRF tokens in POST forms
  • Use AJAX headers for async requests
  • Avoid disabling CSRF unless absolutely required

? Try It Yourself

  • Submit a form without CSRF token
  • Add token to AJAX headers
  • Test @csrf_exempt on a sample API view