Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django/ajax CSRF token missing

I have the following ajax function which is giving me a cross site forgery request token error once I get past the minimumlengthinput of 3 with the select2 control. Knowing this I attempted to add { csrfmiddlewaretoken: '{{ csrf_token }}' }, to my data:. After adding the csrfmiddlewaretoken I'm still getting the CSRF token missing or incorrect error. I believe it has something to do with the my function for the searchFilter and searchPage follows. What is the proper way to do this?

// using jQuery
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;
}
var csrftoken = getCookie('csrftoken');

$(document).ready(function () {
    $('.selectuserlist').select2({
      minimumInputLength: 3,
      allowClear: true,
      placeholder: {
        id: -1,
        text: 'Enter the 3-4 user id.',
      },
      ajax: {
        type: 'POST',
        url: '',
        contentType: 'application/json; charset=utf-8',
        async: false,
        dataType: 'json',
        data: { csrfmiddlewaretoken: csrftoken },

        function(params) {
          return "{'searchFilter':'" + (params.term || '') + "','searchPage':'" + (params.page || 1) + "'}";
        },

        processResults: function (res, params) {
            var jsonData = JSON.parse(res.d);
            params.page = params.page || 1;
            var data = { more: (jsonData[0] != undefined ? jsonData[0].MoreStatus : false), results: [] }, i;
            for (i = 0; i < jsonData.length; i++) {
              data.results.push({ id: jsonData[i].ID, text: jsonData[i].Value });
            }

            return {
              results: data.results,
              pagination: { more: data.more,
              },
            };
          },
      },
    });

  });

My view has the POST method and csrf_token as well.

  {% block content %}
  <form action = "{% url 'multiresult' %}" form method = "POST">
      {% csrf_token %}
  {% block extra_js %}
      {{ block.super }}
      {{ form.media }}

The response from the console is

Forbidden (CSRF token missing or incorrect.): /search/multisearch/ [29/Mar/2018 09:14:52] "POST /search/multisearch/ HTTP/1.1" 403 2502

like image 459
user1470034 Avatar asked Jul 14 '26 19:07

user1470034


2 Answers

You have to include the csrf_token as header:

var csrftoken = $("[name=csrfmiddlewaretoken]").val();

//example ajax
$.ajax({
    url: url,
    type: 'POST',
    headers:{
        "X-CSRFToken": csrftoken
    },
    data: data,
    cache: true,
});

Also make sure that CSRF_COOKIE_SECURE = False if you're not on ssl. If you're using ssl set it to True.

Whether to use a secure cookie for the CSRF cookie. If this is set to True, the cookie will be marked as “secure,” which means browsers may ensure that the cookie is only sent with an HTTPS connection.

like image 158
King Reload Avatar answered Jul 17 '26 15:07

King Reload


A mixture of JS and Django template language helped solve this.

  $.ajax({
         type: 'POST',
         headers:{
        "X-CSRFToken": '{{ csrf_token }}'
         }
  })
like image 24
firedust Avatar answered Jul 17 '26 17:07

firedust