【发布时间】:2019-03-22 07:01:11
【问题描述】:
我有一个表格:
<form action="{% url "some_url" %}" method="post">
{% csrf_token %}
<input type="text">Text Input
<button type="submit">Submit</button>
</form>
通过 AJAX 提交的内容:
$(function () {
$('form').submit(function (e) {
e.preventDefault();
$.post($(this).attr('action'), $(this).serialize(), function (response) {
console.log(response);
});
});
});
指向此视图的 URL 路由:
class SomeView(View):
def post(self, request, *args, **kwargs):
context = dict(**some_data)
rendered_html = render_to_string('some_template.html', context, RequestContext(self.request))
return JsonResponse(dict(html=rendered_html))
所有这些都有效。问题是它在没有发送 CSRF 令牌时也有效,我得到了完全相同的成功响应:
$.post($(this).attr('action'), function (response) {
console.log(response);
});
由于缺少 CSRF 令牌,我预计会引发某种错误。
显而易见:CsrfViewMiddleware 在MIDDLEWARE_CLASSES 之内。
在不发送令牌时显式使用csrf_token 的结果是一样的:
method_decorator(csrf_protect)
def dispatch(self, request, *args, **kwargs):
return super(SomeView, self).dispatch(request, *args, **kwargs)
我可以做些什么来强制其验证?
【问题讨论】:
-
您有自定义的
MIDDLEWARE设置吗?您能否确认django.middleware.csrf.CsrfViewMiddleware处于活动状态? docs.djangoproject.com/en/2.1/ref/csrf/#how-to-use-it -
@HåkenLid 正如我所说,它位于
MIDDLEWARE_CLASSES。有什么方法可以在运行时检查它是否确实处于活动状态,只是为了确保? (如果一开始没有激活,我确信{% csrf_token %}会输出一个空字符串,但我得到的是一个实际的令牌。 -
@dabadaba 可能 CSRF 令牌是在 cookie 中发送的。因此,无论您发布什么,cookie 都会发送到服务器。阅读此处了解更多详情:docs.djangoproject.com/en/2.1/ref/csrf
-
尝试使用新的隐身窗口,或使用浏览器开发工具检查 cookie。我认为如果您在当前浏览器会话中访问了任何使用
{% csrf_token %}的页面,则设置了 csrf cookie。 Cookies 包含在jQuery.post请求中,并被 csrf 中间件接受。 -
就是这样,令牌在cookie中发送。各位大佬可以发帖回答,我采纳。感谢您的帮助!
标签: python django csrf django-1.8