“CSRF令牌丢失或不正确”而通过Django中的AJAX发布参数 [英] "CSRF token missing or incorrect" while post parameter via AJAX in Django
问题描述
我尝试发布参数,如
jQuery.ajax(
{
'type': 'POST',
'url': url,
'contentType': 'application/json',
'data': "{content:'xxx'}",
'dataType': 'json',
'success': rateReviewResult
}
);
但是,Django返回禁止403. CSRF验证失败。请求已中止。
我正在使用'django.middleware.csrf.CsrfViewMiddleware'
,无法找到如何防止此问题
However, Django return Forbidden 403. CSRF verification failed. Request aborted.
I am using 'django.middleware.csrf.CsrfViewMiddleware'
and couldn't find how I can prevent this problem without compromising security.
推荐答案
您可以通过两种不同的方式使AJAX发布请求:
You can make AJAX post request in two different ways:
-
告诉您不要检查csrf令牌。这可以通过使用装饰器
@csrf_exempt
完成,如下所示:
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def your_view_name(request):
...
要在每个AJAX请求中嵌入一个csrf标记,对于jQuery可能是:
To embed a csrf token in each AJAX request, for jQuery it may be:
$(function () {
$.ajaxSetup({
headers: { "X-CSRFToken": getCookie("csrftoken") }
});
});
其中 getCookie
函数检索csrf令牌饼干。我使用以下实现:
Where the getCookie
function retrieves csrf token from cookies. I use the following implementation:
function getCookie(c_name)
{
if (document.cookie.length > 0)
{
c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1)
{
c_start = c_start + c_name.length + 1;
c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) c_end = document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return "";
}
另外,jQuery 有一个插件用于访问cookies,如下所示:
Also, jQuery has a plugin for accessing cookies, something like that:
// set cookie
$.cookie('cookiename', 'cookievalue');<br>
// read cookie
var myCookie = $.cookie('cookiename');<br>
// delete cookie
$.cookie('cookiename', null);
这篇关于“CSRF令牌丢失或不正确”而通过Django中的AJAX发布参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!