CsrfViewMiddleware
- Trigger
- An unsafe request failed the Origin, Referer or token check
- How to tell
- The CSRF failure view runs; the reason goes to the django.security.csrf logger as a warning
Find why Django returns 403: CSRF verification failing, a raised PermissionDenied, or a proxy in front. Includes CSRF_TRUSTED_ORIGINS and fetch header fixes.
Django returns 403 Forbidden for two main reasons: CsrfViewMiddleware rejected an unsafe request (POST, PUT, PATCH, DELETE) because the token, Origin or Referer check failed, or your code raised PermissionDenied. Read the reason Django logs for CSRF failures, then fix the token, the trusted origins or the permission check it names.
Four quick questions, then a straight answer.
From your answers, this is quietly costing you traffic and nobody has the hours to chase it. Scaplet finds every affected page, drafts the fixes and tracks how AI answers mention you.
A data platform shipped 46 fixes without a ticket.
This looks handled. Re-check after a redesign, a migration or a big content push; that is when it breaks.
Your site is small and you have the time. Work through the steps on this page, starting with the pages that get the most traffic.
browser -> proxy / load balancer -> WSGI or ASGI server
-> middleware (CsrfViewMiddleware checks Origin/Referer + token) -> 403 CSRF
-> URL resolver -> view
-> view or decorator raises PermissionDenied -> 403 handler
-> response (proxy may add its own 403 before or after Django)The Django CSRF how-to states the default: "By default, a '403 Forbidden' response is sent to the user if an incoming request fails the checks performed by CsrfViewMiddleware." It adds that this usually means a real cross-site forgery or a programming error where the token was left out of a POST form.
Then replay the failing request against your own server with no cookies and no token. This needs your project running locally (adjust the path to a form view):
python manage.py runserver
# in another terminal
curl -i -X POST http://127.0.0.1:8000/your-form/ -d 'name=test'
# Expect: HTTP/1.1 403 Forbidden. Check the runserver console for the CSRF warning
# with its reason text.If that POST returns 403 and your browser form returns 200, the browser is sending something the curl call does not. If both return 403, read the reason text before changing anything.
curl -i https://httpbin.org/status/403
# Expect: HTTP/2 403 followed by headers. Run the same curl -i against your URL
# and compare the Server and Via headers to find which layer answered.<form method="post">
{% csrf_token %}
<button type="submit">Save</button>
</form>const request = new Request(
/* URL */,
{
method: 'POST',
headers: {'X-CSRFToken': csrftoken},
mode: 'same-origin' // Do not send CSRF token to another domain.
}
);
fetch(request).then(function(response) {
// ...
});CSRF_TRUSTED_ORIGINS = ["https://subdomain.example.com", "https://*.example.com"]| Reason | Usual cause | Fix |
|---|---|---|
| Origin checking failed - %s does not match any trusted origins. | The Origin header is a different origin from the one Django sees, often behind HTTPS termination or on another subdomain | Add the full origin, scheme included, to CSRF_TRUSTED_ORIGINS |
| Referer checking failed - no Referer. | A secure request carried neither Origin nor Referer | Stop stripping the Referer header, or send Origin |
| Referer checking failed - Referer is insecure while host is secure. | A page on http posting to an https host | Serve the form over https |
| CSRF cookie not set. | No csrftoken cookie was sent | Render a template with csrf_token, or use ensure_csrf_cookie on the view |
| CSRF token missing. | The cookie was present but the form field or header was not | Add the token to the form or the X-CSRFToken header |
In a template form, the token goes inside the form element:
For JavaScript, the Django how-to reads the csrftoken cookie and sends it in the X-CSRFToken header with mode: 'same-origin' so it is not sent to another domain:
If your form lives on another origin, the Django settings reference says to list that origin. Its wildcard form allows all subdomains:
PermissionDenied is raised when a user lacks permission for the requested action. Your own permission checks can raise it directly:The views documentation's testing example shows the matching hook: set handler403 in the root URLconf and the exception is rendered by your function. Handlers set anywhere else have no effect.
from django.http import HttpResponse
def response_error_handler(request, exception=None):
return HttpResponse("Error handler content", status=403)
handler403 = response_error_handlerFor CSRF specifically, the how-to says the default error page is not friendly and names the CSRF_FAILURE_VIEW setting as the place to supply your own. Return an HttpResponseForbidden from it.
from django.core.exceptions import PermissionDenied
def edit_invoice(request, pk):
invoice = get_object_or_404(Invoice, pk=pk)
if invoice.owner_id != request.user.id:
raise PermissionDenied
...PermissionDenied, middleware you added, or a firewall in front. If pages you want indexed return it, fix the rule rather than waiting. See 4xx errors and the guide for a 404 in Django.3 questions people ask next, answered from the sources on this page.
CsrfViewMiddleware checks unsafe methods such as POST, so a GET to the same URL succeeds while the POST fails the Origin, Referer or token check. Include the token in the form or header and add any cross-origin site to CSRF_TRUSTED_ORIGINS.
CSRF failures are logged as warnings to the django.security.csrf logger, and the reason is passed to the CSRF failure view. Match the reason to the table above.
It removes the middleware check for that view, so it only suits endpoints that do not depend on browser cookies. For browser forms, fix the token or the trusted origin instead.
Run the free audit, then approve the fixes. Every change can be undone.