CSRF (Cross-Site Request Forgery) is an attack in which an adversary tricks the user’s browser into sending a request on the user’s behalf.
How Django CSRF Works
- Django creates a CSRF token when a template renders
{% csrf_token %}or a view explicitly requests one - Every HTML form with POST must include a hidden field containing the token
- Django compares the token from the form with the token in the cookie
- If they do not match โ the response is
403 Forbidden
Template Tag
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
{% csrf_token %} generates:
<input type="hidden" name="csrfmiddlewaretoken" value="abc123...">
AJAX Requests
// Get the token from the cookie
function getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
}
fetch('/api/tasks/', {
method: 'POST',
headers: {
'X-CSRFToken': getCookie('csrftoken'),
'Content-Type': 'application/json',
},
body: JSON.stringify({title: 'New Task'}),
});
Exempting an API Endpoint
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def api_endpoint(request):
... # Validate an appropriate non-cookie credential here
Do not add csrf_exempt merely to silence a 403 response. It is appropriate only when the endpoint does not rely on cookie-based authentication and another secure authentication mechanism is enforced. DRF’s SessionAuthentication requires CSRF protection for unsafe methods; token-based authentication does not rely on CSRF tokens.
Middleware
MIDDLEWARE = [
...,
'django.middleware.csrf.CsrfViewMiddleware',
...,
]
The middleware is included by default โ do not remove it.
๐ฌ Comments (0)
No comments yet
Be the first to share your opinion about this article!