我在Linux上开发我的应用程序和AJAX请求正常工作。我已经退出了应用程序在Windows计算机,但AJAX请求失败,我只是得到一个403 Forbidden错误。从网上看,我认为这是与CSRF令牌的问题。在Linux中,我可以看到 csrftoken:在AJAX请求的曲奇AjQzJy3tRZ2awslgdibkDTvQgANFQKmP
。我看不出在Windows中设置的任何cookie。
I developed my application on Linux and the AJAX requests work fine. I have pulled the application to a Windows machine but the AJAX requests fail, I just get a 403 Forbidden error. From looking online, I think it is a problem with the csrf token. In Linux, I can see csrftoken:"AjQzJy3tRZ2awslgdibkDTvQgANFQKmP"
under Cookies of the AJAX requests. I don't see any cookies set in Windows.
这是JavaScript code我用得到的CSRF的cookie。距离 https://docs.djangoproject.com/en/1.8/ref/csrf /
This is the Javascript code I use to get the csrf cookie. It is from https://docs.djangoproject.com/en/1.8/ref/csrf/
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;
}
这是我提出AJAX请求:
This is where I submit the AJAX request:
function refreshInformation(){
$.ajax({
type: "POST",
url: "get_flows_info",
data: {
csrfmiddlewaretoken: getCookie('csrftoken')
}
dataType : "json",
async : true,
error : function(data){
alert('AJAX error:' + data);
},
success : function(json_data){
// do stuff...
},
});
}
这是被请求的观点:
def get_flows_info(request):
if request.is_ajax():
# do stuff...
return HttpResponse(json.dumps(ret), content_type='application/json')
我发现这一点:Django跨站请求伪造支票未能与一个Ajax POST请求 但jQuery的没有任何区别。
I found this: Django CSRF check failing with an Ajax POST request but the jQuery doesn't make any difference.
任何帮助吗?
感谢。
下面是可以做到的:
检查CSRF令牌cookie的名称。
Check CSRF token cookie name.
请参阅 CSRF_COOKIE_NAME
了解详情。
See CSRF_COOKIE_NAME
for more information.
添加 ensure_csrf_cookie
装饰你的看法(一呈现页)。
Add ensure_csrf_cookie
decorator to your view (the one that renders page).
根据的文档:
警告
如果你的观点并没有呈现包含的 csrf_token
模板标签,Django的,还没有设置CSRF令牌的cookie。这是常见的情况下,其中的形式动态添加到页面。为了应对这种情况,Django提供了一个视图修饰迫使cookie的设置: ensure_csrf_cookie()
。
If your view is not rendering a template containing the csrf_token
template tag, Django might not set the CSRF token cookie. This is common in cases where forms are dynamically added to the page. To address this case, Django provides a view decorator which forces setting of the cookie: ensure_csrf_cookie()
.
假设CSRF令牌cookie的名称是 csrftoken
,尝试发送 X-CSRFToken
头。
Assuming that CSRF token cookie name is csrftoken
, try to send X-CSRFToken
header.
$.ajax({
// Your options here.
headers: {'X-CSRFToken': getCookie('csrftoken')}
});
阅读跨站请求伪造保护了解详情。