How Cross-Site Request Forgery (CSRF) token works?

CSRF Protection in Django

  • Django includes built-in CSRF protection using middleware (django.middleware.csrf.CsrfViewMiddleware) which is included in the settings.py file of a django project.
  • When a user loads a page with a form, Django generates a unique CSRF token for the session.

Embedding the Token in Forms

  • The {% csrf_token %} tag is placed inside <form> elements in Django templates.
  • It renders a hidden <input> field containing the CSRF token.
<form method="POST">
    {% csrf_token %}
    <input type="text" name="username">
    <input type="submit" value="Submit">
</form>

After rendering, it becomes:

<input type="hidden" name="csrfmiddlewaretoken" value="some_random_token">

Verification on the Server

  • When the form is submitted, Django checks the CSRF token sent in the request against the one stored in the user’s session.
  • If they match, the request is processed; otherwise, Django rejects the request with a 403 Forbidden error.

When is {% csrf_token %} Required?

  • Always use {% csrf_token %} in HTML forms that use POST requests.
  • Not needed for GET requests since they don’t modify data.
  • Necessary in AJAX requests that modify data (e.g., POST, PUT, DELETE).

CSRF Protection in AJAX Requests:

If using JavaScript (e.g., jQuery) for AJAX requests:

$.ajax({
    url: "/submit/",
    type: "POST",
    headers: { "X-CSRFToken": getCookie("csrftoken") }, // Send CSRF token in headers
    data: { username: "john" }
});

Summary:

  • {% csrf_token %} prevents CSRF attacks by embedding a unique token in forms.
  • Django validates the token before processing POST requests.
  • Essential for security in web applications handling form submissions.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *