Valorad Valorad - 3 months ago 58
Ajax Question

Django AJAX POST login CSRF error in IE, EDGE, etc

I'm using Django 1.10.

I want to log in via Jquery AJAX, but CSRF is set on.

In order to pass the CSRF check, I have the following code (in a standalone js file).



/* CSRF-config Start */
$.ajaxSetup({
beforeSend: function(xhr, settings) {
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});
$(document).ajaxSend(function( event, xhr, settings ) {
if (settings.type == 'POST' || settings.type == 'PUT' || settings.type == 'DELETE') {
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});
/* CSRF-config End */





Chrome works perfectly here, logged in with no issues.

However, when I switch to IE, Edge, etc. The following error occurred:

"""

Forbidden (CSRF cookie not set.): /login/

[25/Aug/2016 08:58:42] "POST /login/ HTTP/1.1" 403 2857

"""

The code I have seems not working at all. :(

Answer

Here! I figured out a solution.

The following code should ONLY be written in template html page.

DO NOT leave it to a standalone JS file.

Delete other related CSRF AJAXSetup code in case of conflicts.

<!-- Bla bla bla your login form, input, etc. -->
<script>
  $.ajaxSetup({
      data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
  });
</script>