Proper Django CSRF validation using fetch post request

放肆的年华 提交于 2019-12-18 13:38:29

问题


I'm trying to use JavaScript's fetch library to make a form submission to my Django application. However no matter what I do it still complains about CSRF validation.

The docs on Ajax mentions specifying a header which I have tried.

I've also tried grabbing the token from the templatetag and adding it to the form data.

Neither approach seems to work.

Here is the basic code that includes both the form value and the header:

let data = new FormData();
data.append('file', file);;
data.append('fileName', file.name);
// add form input from hidden input elsewhere on the page
data.append('csrfmiddlewaretoken', $('#csrf-helper input[name="csrfmiddlewaretoken"]').attr('value'));
let headers = new Headers();
// add header from cookie
const csrftoken = Cookies.get('csrftoken');
headers.append('X-CSRFToken', csrftoken);
fetch("/upload/", {
    method: 'POST',
    body: data,
    headers: headers,
})

I'm able to get this working with JQuery, but wanted to try using fetch.


回答1:


Figured this out. The issue is that fetch doesn't include cookies by default.

Simple solution is to add credentials: "same-origin" to the request and it works (with the form field but without the headers). Here's the working code:

let data = new FormData();
data.append('file', file);;
data.append('fileName', file.name);
// add form input from hidden input elsewhere on the page
data.append('csrfmiddlewaretoken', $('#csrf-helper input[name="csrfmiddlewaretoken"]').attr('value'));
fetch("/upload/", {
    method: 'POST',
    body: data,
    credentials: 'same-origin',
})



回答2:


Your question is very close to success. Here is a json way if you do not want the form method. Btw, @Cory's form method is very neat.

  1. Neat way with 3rd library
let data = {
    'file': file,
    'fileName': file.name,
};
// You have to download 3rd Cookies library
// https://docs.djangoproject.com/en/dev/ref/csrf/#ajax
let csrftoken = Cookies.get('csrftoken');
let response = fetch("/upload/", {
    method: 'POST',
    body: JSON.stringify(data),
    headers: { "X-CSRFToken": csrftoken },
})

2. Another cumbersome way, but without any 3rd library

let data = {
    'file': file,
    'fileName': file.name,
};
let csrftoken = getCookie('csrftoken');
let response = fetch("/upload/", {
    method: 'POST',
    body: JSON.stringify(data),
    headers: { "X-CSRFToken": csrftoken },
})

// The following function are copying from 
// https://docs.djangoproject.com/en/dev/ref/csrf/#ajax
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 = cookies[i].trim();
            // 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;
}


来源:https://stackoverflow.com/questions/43606056/proper-django-csrf-validation-using-fetch-post-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!