“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 返回 Forbidden 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
函数从 cookie 中检索 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 有一个插件 用于访问 cookie,类似于:
Also, jQuery has a plugin for accessing cookies, something like that:
// set cookie
$.cookie('cookiename', 'cookievalue');
// read cookie
var myCookie = $.cookie('cookiename');
// delete cookie
$.cookie('cookiename', null);
这篇关于“CSRF 令牌丢失或不正确"在Django中通过AJAX发布参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!