Forbidden (CSRF token missing or incorrect)

16 views
Skip to first unread message

Abdul Qoyyuum

unread,
May 21, 2019, 5:52:26 PM5/21/19
to Django users
Hi Django Devs,

Got a problem that I don't understand what's going on or why its gone missing.

Logs says:
csrf.py:process_view#184: Forbidden (CSRF token missing or incorrect.)


The necessary code is in there:

$("document").ready(function () {

   
//------------------------------------
   
//Setup X-CSRFToken header for
   
//XHR requests.
   
//------------------------------------
    $
.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'));
           
}
       
}
   
});



However, on the Network DevTools, it shows that the CSRFToken is null

Host: django.project.localhost
User-Agent: Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:66.0) Gecko/20100101 Firefox/66.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Referer: https://xxx.xxx.xxx.xxx/someURL
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-CSRFToken: null
X-Requested-With: XMLHttpRequest
Content-Length: 347
Connection: keep-alive
Cookie: cookiesession1=05D05AA6TMRNUKHVEOY2WSF7DYB0F3; csrftoken=CY9TvQT97LpOZDhF6xZldBrAX4Igyt; sessionid=1e4c34b81175fb33465c0197e4ec3a

So as we can see the csrftoken is there, but not able to get it and store in X-CSRFToken, even though the code hasn't changed, now its not working.

Reply all
Reply to author
Forward
0 new messages