← Back to Django Course | Chapter 15: Security, Caching & Deployment | Lesson 3 of 9

CSRF Security का Overview

CSRF protection एक secret handshake जैसा है जो prove करता है कि एक form असल में आपकी अपनी website से आया, न कि कहीं और से भेजी गई एक trick।
Syntax
markup
<form method="post">
  {% csrf_token %}
  <!-- form fields -->
</form>

CSRF Protection क्या रोकता है

Protection के बिना, एक malicious website एक hidden form embed कर सकती है जो victim की existing login session उपयोग करके आपकी site पर submit होता है, वे actions perform करते हुए जिनसे victim ने कभी agree नहीं किया।

Django का CSRF token हर form submission को उस page से tie करता है जिसने इसे legitimately render किया।

Note: CSRF protection सिर्फ state-changing requests जैसे POST के लिए मायने रखता है, read-only GET requests के लिए नहीं।

उदाहरण: What CSRF Protection Prevents

Without protection, a malicious website could embed a hidden form that submits to your site using the victim's existing login session, performing actions the victim never agreed to. Django's CSRF token ties every form submission to the page that legitimately rendered it.

markup
<!-- templates/donate.html -->
<form method="post">
    {% csrf_token %}
    <label for="amount">Amount</label>
    <input type="number" id="amount" name="amount">
    <button type="submit">Donate</button>
</form>
{# Django-only code -- models.py/views.py/urls.py/settings.py snippets, or template markup using Django template tags/variables -- can't run standalone via Judge0 or the browser preview, since it needs a real Django project. Only this course's pure-Python examples (example_lang == 'python', no Django imports) are actually runnable, so those still get the button below. #}

Middleware इसे कैसे जांचता है

django.middleware.csrf.CsrfViewMiddleware settings.py में default रूप से enabled है। हर POST request पर, यह form में submitted token को user की session/cookie में stored token से compare करता है, अगर वे match न करें तो request को 403 के साथ reject करते हुए।

Warning: CSRF checks run होने के लिए middleware MIDDLEWARE में रहना चाहिए।

उदाहरण: How the Middleware Checks It

django.middleware.csrf.CsrfViewMiddleware is enabled by default in settings.py. On every POST request, it compares the token submitted in the form against the one stored in the user's session/cookie, rejecting the request with a 403 if they don't match.

markup
# settings.py -- CSRF middleware is on by default
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
]
{# Django-only code -- models.py/views.py/urls.py/settings.py snippets, or template markup using Django template tags/variables -- can't run standalone via Judge0 or the browser preview, since it needs a real Django project. Only this course's pure-Python examples (example_lang == 'python', no Django imports) are actually runnable, so those still get the button below. #}

JavaScript से Token भेजना

एक plain HTML form के बजाय fetch() या AJAX के through एक POST request submit करते समय, CSRF token को cookie से पढ़ा जाना चाहिए और एक request header के रूप में भेजा जाना चाहिए।

उदाहरण: Sending the Token from JavaScript

When submitting a POST request via fetch() or AJAX instead of a plain HTML form, the CSRF token must be read from the cookie and sent as a request header.

markup
// Read the csrftoken cookie Django sets automatically
function getCookie(name) {
    const match = document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)');
    return match ? match.pop() : '';
}

fetch('/donate/', {
    method: 'POST',
    headers: { 'X-CSRFToken': getCookie('csrftoken') },
    body: new URLSearchParams({ amount: 10 }),
});
{# Django-only code -- models.py/views.py/urls.py/settings.py snippets, or template markup using Django template tags/variables -- can't run standalone via Judge0 or the browser preview, since it needs a real Django project. Only this course's pure-Python examples (example_lang == 'python', no Django imports) are actually runnable, so those still get the button below. #}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. यह समझने के बजाय कि यह क्यों required है, एक confusing 403 error fix करने के लिए form से {% csrf_token %} हटाना।
  2. सिर्फ एक error गायब करने के लिए एक view पर @csrf_exempt उपयोग करना, इसे cross-site attacks के लिए खोलते हुए।
  3. यह भूल जाना कि AJAX POST requests को भी CSRF token एक header के रूप में भेजना होता है, सिर्फ HTML forms में नहीं।
चैप्टर सारांश
  • CSRF (Cross-Site Request Forgery) एक logged-in user के browser को ऐसा request submit करने के लिए trick करता है जो उसने करने का इरादा नहीं रखा था।
  • Django का CsrfViewMiddleware हर unsafe request (POST, PUT, DELETE) पर एक valid token जांचता है।
  • POST से submit होने वाला हर form <form> tag के अंदर {% csrf_token %} include करना चाहिए।
  • Token prove करता है कि request असल में आपकी site के अपने page से आया, किसी attacker के page से नहीं।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.