On Sat, 2011-02-19 at 12:00 +0100, Sayane wrote: > There's a problem with CSRF Protection and XHR requests. It works > perfectly if 'csrftoken' cookie has been set already. But what if it's > not? > Cookie with token will be set only, if META["CSRF_COOKIE_USED"] is > True [1]. It's set to True in function get_token() [2]. get_token() is > called in CsrfResponseMiddleware [3] (It's deprecated, i'm not using > it) and in 'csrf' context processor (note - calling it is lazy, so I > need to use {% csrf_token %} or at least get the value of csrf_token > variable). > > But in my project i'm not using {% csrf_token %} anywhere. According > to documentation [5] I'm not required to do anything else, but write a > simple javascript code. Actually it's not true. I have to put > "request.META['CSRF_COOKIE_USED'] = True" line in every view (or write > appropriate decorator).
> What is more, it will affect users who didn't come across page where > csrf_token is used, but their browser needs to send xhr post request. I guess this is an edge case - it would typically be very rare for someone to be doing POST AJAX requests who has never hit a page with {% csrf_token %} on it - even if it was just the login page. The docs for AJAX are meant to be in *addition* to the docs on the rest of the page, which state, among other things, that you need to include a {% csrf_token %} on the page. This bit (step 2 in "How to use it") could be clarified for the case of AJAX-only sites. So, my suggested solution is some small doc fixes, and the addition of a decorator 'ensure_csrf_cookie' that ensures the cookie will be sent. The correct way to implement this decorator is to simply add a call to django.middleware.csrf.get_token(). META["CSRF_COOKIE_USED"] is an implementation detail that we are free to change, so don't rely on setting that explicitly. If you would like to open a ticket to track this, that would be great. Regards, Luke -- "Agony: Not all pain is gain." (despair.com) Luke Plant || http://lukeplant.me.uk/ -- You received this message because you are subscribed to the Google Groups "Django developers" group. To post to this group, send email to django-developers@googlegroups.com. To unsubscribe from this group, send email to django-developers+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-developers?hl=en.