Opened 13 years ago
Closed 13 years ago
#16164 closed Bug (worksforme)
Suggested approach for CSRF in AJAX requests doesn't work when cookie not set
Reported by: | anonymous | Owned by: | nobody |
---|---|---|---|
Component: | CSRF | Version: | 1.3 |
Severity: | Normal | Keywords: | |
Cc: | Triage Stage: | Unreviewed | |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
Looking at the CSRF documentation, if the suggested approach is implemented, there's a risk it will not work. The jQuery hook code that's exemplified looks for the csrftoken cookie value. However, if the AJAX requests are made from a session missing that cookie, the CSRF validation will ultimately fail. This cookie can be missing since it's only added to responses if a template or view has explicitly requested the cookie (thus adding CSRF_COOKIE_USED
to the request.META, which is checked for [source:django/trunk/django/middleware/csrf.py@16201#L200 here]). The documentation would need to call this out and/or provide a way to manually force this cookie to be set on responses including the AJAX-driven form. Alternatively, the middleware could be changed to add the cookie regardless of whether or not it's been explicitly requested.
This is a duplicate of #15925 and #15354 and it was fixed in r16192.
See https://docs.djangoproject.com/en/dev//ref/contrib/csrf/#django.views.decorators.csrf.ensure_csrf_cookie