A
A
Artyom Innokentiev2015-09-15 00:04:31
JavaScript
Artyom Innokentiev, 2015-09-15 00:04:31

AJAX, Django, CSRF: Why is there a 403 error?

A snippet of the index.html file :

<div id = "task_adder">
        <input type = "text" id = "task_text"><input type = "button" value = "Добавить задачу" id = "add">
      </div>

      <div id = "control_panel">
        <input type = "button" value = "Удалить отмеченные" id = "delete">
        <input type = "button" value = "Отметить выполненным" id = "done">
        <input type = "button" value = "Вернуть в активное" id = "backward">
      </div>


A snippet of the csrf.js file :
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');

  function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}

$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});


Snippet of index.js file :
$.ajax(
  {
    url: to_url,
    type: 'POST',
    data: dict,
    success: function()
    {
      $('#task_list').load('/ #task_list')
    },
  });


I did not add the form and {% csrf_token %} to index.html . csrf_token seems to be generated in the csrf.js file , but it is not passed. Why?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
Oleg, 2015-09-15
@artinnok

Actually csrf.js doesn't generate csrf token, it only reads it from cookies and puts it in HTTP header so that Django (CsrfViewMiddleware) can read it and protect against CSRF attack if the token is invalid.
Thus, to add this same csrf token to cookies, it is necessary that:
1. CsrfViewMiddleware must be specified in MIDDLEWARE_CLASSES
2. In the template, you need to insert the {% csrf_token %} tag into some form, if you do not have any suitable form, then use the ensure_csrf_cookie decorator ( https://docs.djangoproject.com/en/1.8/ref/csrf/#dj... ) to decorate view c index.html.

I
IvanOne, 2015-09-15
@IvanOne

Or use the decorator from django.views.decorators.csrf import csrf_exempt
Not the best idea, I know.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question