Django的中间件抛出403错误使用AJAX HTTPS POST抛出、中间件、错误、Django

2023-09-10 17:53:40 作者:再回首,已成往事

我是新来的许多作品在这里(Django的/阿贾克斯等),因此,虽然我理解高层CSFR的画面,我没有在细节上完全处理。

我需要一个请求转换能放入由于被传递的数据量较大。高的水平,我在做一个AJAX POST API调用来通过HTTPS一个Django应用程序。该调用是从页面被所在的同一个域。

不过,我不断收到一个CSRF的cookie没有设置的错误。

我使用的Django 1.4

让过去CSRF保护,我已经包括在X-CSFRToken如标题中提到的其他职位这里包含了{{csrf_token}}在发布的数据标签。不过,它看起来像犯规该标签被替换令牌。的X CSFRToken值被发送为NULL的请求。不知道为什么它没有被置1。

我在IM pression,我不需要用ensure_csrf_cookie()在页面视图,因为我得到这个职位在ajaxSetup前的饼干,但我想这一点。

想法,我做错了吗?

相关code:

  SITEURL =htt​​ps://开头本地主机:8443 /

$ .ajaxSetup({
     beforeSend:功能(XHR,设置){
         函数的getCookie(名字){
             VAR cookieValue = NULL;
             如果(document.cookie中和放大器;&安培;!的document.cookie =''){
                 VAR饼干= document.cookie.split(';');
                 对于(VAR I = 0; I< cookies.length;我++){
                     VAR饼干= jQuery.trim(饼干[I]);
                 如果(cookie.substring(0,name.length + 1)==(名称+'=')){
                     cookieValue =去codeURIComponent(co​​okie.substring(name.length + 1));
                     打破;
                 }
             }
         }
         返回cookieValue;
         }
         如果(新正则表达式(^+ siteUrl.replace(\\,\\\\)+。*)。试验(settings.url)){
             //只有从我们的网站令牌发送到URL。
             xhr.setRequestHeader(X-CSRFToken,的getCookie('csrftoken'));
         }
     }
});


$阿贾克斯({
    网址:submitUrl,
    数据:{network_ids:JSON.stringify(network_ids)
            csrfmiddlewaretoken:{{csrf_token}}},
    键入:POST,
    跨域:真正的,
    数据类型:JSON,
    cotentType:应用/ JSON的,
    成功:函数(MYDATA){
        执行console.log(MYDATA);
    },
    错误:函数(jqXHR,textStatus,errorThrown){警报(textStatus);警报(errorThrown)}
})
 

解决方案

您有几种选择: 这code清单显示过得好从一个cookie的CSRF令牌: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

 函数的getCookie(名字){
    VAR cookieValue = NULL;
    如果(document.cookie中和放大器;&安培;!的document.cookie =''){
        VAR饼干= document.cookie.split(';');
        对于(VAR I = 0; I< cookies.length;我++){
            VAR饼干= jQuery.trim(饼干[I]);
            //这是否cookie字符串与我们想要的名字么?
            如果(cookie.substring(0,name.length + 1)==(名称+'=')){
                cookieValue =去codeURIComponent(co​​okie.substring(name.length + 1));
                打破;
            }
        }
    }
    返回cookieValue;
}
的getCookie('csrftoken');
 
Django Ajax

和假设的JavaScript函数就是提交给Django视图,你可以告诉大家,观点忽略CSRF保护。 https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#django.views.decorators.csrf.csrf_exempt

 从django.views.decorators.csrf进口csrf_exempt

@csrf_exempt
高清my_view(要求):
    返回的Htt presponse(世界,你好)
 

I'm new to many pieces here (Django/Ajax etc), so while I understand the high-level CSFR picture, I dont have a complete handle on the details.

I needed to convert a request from GET to PUT due to the larger amount of data being passed. High level, I'm making an AJAX POST API call to a django app over HTTPS. The call is made to the same domain from where the page is served.

However, I keep getting a 'CSRF cookie not set' error.

I'm using Django 1.4

To get past CSRF protection, I have included the X-CSFRToken as mentioned in other posts here in the header and included the {{ csrf_token }} tag in the data posted. However, it doesnt look like that tag gets replaced with the token. X-CSFRToken value gets sent as NULL on the request. Not sure why it doesnt get set.

I'm under the impression that I dont need to use ensure_csrf_cookie() in the page view as I get the cookie before the POST in ajaxSetup, but I tried that as well.

Ideas what I'm doing wrong?

Relevant code:

siteUrl = "https://localhost:8443/"

$.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]);
                 if (cookie.substring(0, name.length + 1) == (name + '=')) {
                     cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                     break;
                 }
             }
         }
         return cookieValue;
         }
         if (new RegExp("^"+siteUrl.replace("\\","\\\\")+".*").test(settings.url)) {
             // Only send the token to URLs from our site.
             xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
         }
     } 
});


$.ajax({
    url: submitUrl,
    data: {'network_ids': JSON.stringify(network_ids),
            'csrfmiddlewaretoken': '{{ csrf_token }}'},
    type: 'POST',
    crossDomain: true,
    dataType: 'json',
    cotentType: 'application/json',
    success: function(mydata) {
        console.log(mydata);
    },
    error: function(jqXHR, textStatus, errorThrown) {alert(textStatus); alert(errorThrown)}
})

解决方案

You have several choices: This code listing shows you getting the CSRF token from a cookie: https://docs.djangoproject.com/en/dev/ref/contrib/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 = 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;
}
getCookie('csrftoken');

and assuming that the javascript function is submitting to a django view, you can tell that view to ignore csrf protection. https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#django.views.decorators.csrf.csrf_exempt

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def my_view(request):
    return HttpResponse('Hello world')