From dcc76fa469fd84d2ef78cf855cab53d497151348 Mon Sep 17 00:00:00 2001 From: raymondr Date: Wed, 26 Jun 2013 13:29:53 -0600 Subject: [PATCH 1/2] Update dajaxice.core.js Implement DAJAXICE_FETCH_CSRF_FROM_FIELD If you have set httponly attribute on the CSRFcookie, javascript will not be able to read CSRF cookie. Instead we can fetch the CSRF token from the hidden field generated in the form by CSRF middleware. --- dajaxice/templates/dajaxice/dajaxice.core.js | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/dajaxice/templates/dajaxice/dajaxice.core.js b/dajaxice/templates/dajaxice/dajaxice.core.js index a6ceed5..2bbd419 100644 --- a/dajaxice/templates/dajaxice/dajaxice.core.js +++ b/dajaxice/templates/dajaxice/dajaxice.core.js @@ -26,6 +26,15 @@ var Dajaxice = { return cookieValue; }, + get_csrf_id: function() + { + {% if dajaxice_config.DAJAXICE_FETCH_CSRF_FROM_FIELD %} + return document.getElementsByName('csrfmiddlewaretoken')[0].value; + {% else %} + return Dajaxice.get_cookie('{{ dajaxice_config.django_settings.CSRF_COOKIE_NAME }}') + {% endif %} + }, + call: function(dajaxice_function, method, dajaxice_callback, argv, custom_settings) { var custom_settings = custom_settings || {}, @@ -45,7 +54,7 @@ var Dajaxice = { oXMLHttpRequest.open(method, endpoint); oXMLHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); oXMLHttpRequest.setRequestHeader("X-Requested-With", "XMLHttpRequest"); - oXMLHttpRequest.setRequestHeader("X-CSRFToken", Dajaxice.get_cookie('{{ dajaxice_config.django_settings.CSRF_COOKIE_NAME }}')); + oXMLHttpRequest.setRequestHeader("X-CSRFToken", Dajaxice.get_csrf_id()); oXMLHttpRequest.onreadystatechange = function() { if (this.readyState == XMLHttpRequest.DONE) { if(this.responseText == Dajaxice.EXCEPTION || !(this.status in Dajaxice.valid_http_responses())){ From 44fd1789ef0cb732875c669532587d0edeeb4975 Mon Sep 17 00:00:00 2001 From: raymondr Date: Wed, 26 Jun 2013 13:37:15 -0600 Subject: [PATCH 2/2] Update available-settings.rst --- docs/available-settings.rst | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/docs/available-settings.rst b/docs/available-settings.rst index ac70aee..e69b085 100644 --- a/docs/available-settings.rst +++ b/docs/available-settings.rst @@ -36,3 +36,12 @@ Default data sent when an exception occurs. Defaults to ``"DAJAXICE_EXCEPTION"`` Optional: ``True`` + +DAJAXICE_FETCH_CSRF_FROM_FIELD +------------------------------ + +Should we fetch the CSRF token from a form field? If False, then fetch from cookie. + +Defaults to ``False`` + +Optional: ``True``