Suggested approach for CSRF in AJAX requests doesn't work when cookie not set
|Reported by:||anonymous||Owned by:||nobody|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
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.