Django:使用S3,Cloudfront时,跨站点请求伪造保护不起作用

时间:2017-01-24 16:10:53

标签: ajax django amazon-s3 cors csrf

我使用jsAWS S3管理静态文件,包括AWS CloudFront个文件。

我有一个代码发送ajax POST请求(我的django视图之一),此a.js文件位于S3

我意识到我遇到了一些跨域问题,因此我在https://docs.djangoproject.com/en/1.10/ref/csrf/#ajax中复制并粘贴了一些代码。这是我的js代码:

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);
        }
    }
});


$.ajax({
    type: "POST",
    url: '/orders/pay-check/',
    data: {
        imp_uid : rsp.imp_uid,
        merchant_uid : rsp.merchant_uid
    }, // form date가 아니기 때문에, 맨위에 ajax cookie 세팅을 해줘야함
    success: function(data) {
        ...
    }
});

但它发生csrf_token错误!所以我详细查看了这段代码并尝试编辑代码的一部分:

第一种方式:在POST中添加csrfSafeMethod并移除this.crossdomain

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

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

第二种方式:只需在POST中添加csrfSafeMethod

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

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

第三种方式:在POST中添加csrfSafeMethod并将!this.crossDomain更改为this.crossDomain

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

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

但所有这些情况都不起作用!! ....

真的想得到一些建议。感谢。

**编辑**

我有点奇怪。

如果我打开Chorme development tool控制台并打印document.cookie,其输出不包括我本地开发环境中包含的csrftoken ....仅在生产环境中不包含它出现了

0 个答案:

没有答案