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.
Django verifies CSRF tokens for unsafe HTTP methods like POST, PUT, and DELETE. Tokens are automatically added to forms and validated on submission.
// Enable CSRF middleware in Django
MIDDLEWARE = [
'django.middleware.csrf.CsrfViewMiddleware',
]
// Adding CSRF token to a Django form
<form method="post">
{% csrf_token %}
<button type="submit">Submit</button>
</form>
// Sending CSRF token via AJAX request
var csrftoken = $('[name="csrfmiddlewaretoken"]').val();
$.ajax({
type: "POST",
url: "/some-url/",
headers: {'X-CSRFToken': csrftoken}
});
If a request is sent without a valid CSRF token, Django responds with a 403 Forbidden error, blocking malicious activity.
// Custom CSRF failure handler
from django.http import HttpResponseForbidden
def csrf_failure(request, reason=""):
return HttpResponseForbidden("CSRF token missing or invalid")
Think of the CSRF token as a secret handshake between the browser and server. If the handshake fails, access is denied.
{% csrf_token %} in forms@csrf_exempt cautiously