#15469: CSRF/Ajax/JQuery - Token is set to be inserted on both GET and POST ----------------------------------------+-------------------------------- Reporter: goran@… | Owner: nobody Status: new | Milestone: Component: contrib.csrf | Version: SVN Resolution: | Keywords: csrf,ajax,jquery Triage Stage: Accepted | Has patch: 0 Needs documentation: 0 | Needs tests: 0 Patch needs improvement: 0 | ----------------------------------------+-------------------------------- Changes (by aaugustin):
* cc: aymeric.augustin@… (added) Comment: `settings.type` is uppercased at line 6674 of jQuery.js: `s.type = s.type.toUpperCase();` The `ajaxSend` event is fired at line 6756: `globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );` So we can safely assume that `settings.type` is uppercase. ---- I also noticed jQuery computes `settings.hasContent` like this: `s.hasContent = !rnoContent.test( s.type );` where `rnoContent = /^(?:GET|HEAD)$/`. This parameter is internal to jQuery; it is used, for instance, to determine whether to send the X-Requested-With header. So the test for safe requests could be: `if (!settings.hasContent) { /* send token on local requests */ }` ---- Finally, since jQuery 1.5, `settings.crossDomain` tells whether the request is cross-domain — see around line 6647. Hence my suggestion: {{{ $('html').ajaxSend(function(event, xhr, settings) { // ... define getCookie here ... // only send the CSRF token for local unsafe requests — safe requests are GET and HEAD if (!s.crossDomain && s.hasContent ) { xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); } } }}} ---- One last thought: we could mention the possibility to use http://plugins.jquery.com/project/Cookie and this code: {{{ $('html').ajaxSend(function(event, xhr, settings) { // only send the CSRF token for local unsafe requests (safe requests are GET and HEAD) if (!s.crossDomain && s.hasContent ) { xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken')); } } }}} ---- Any opinions on this before I propose a patch? -- Ticket URL: <http://code.djangoproject.com/ticket/15469#comment:3> Django <http://code.djangoproject.com/> The Web framework for perfectionists with deadlines. -- You received this message because you are subscribed to the Google Groups "Django updates" group. To post to this group, send email to django-updates@googlegroups.com. To unsubscribe from this group, send email to django-updates+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-updates?hl=en.