Django的 - CSRF验证失败 - 从形式发送数据的静态网站,我的Django应用程序
问题描述:
我的设置:Django的 - CSRF验证失败 - 从形式发送数据的静态网站,我的Django应用程序
- 静态网站的登陆页面通过AWS S3 (welcome.mydomain.com)提供服务。
- 一个django应用程序(Django的1.8与python 2.7) 可通过子域(app.mydomain.com)访问。
我想添加一个联系表单,这是我的静态网站的一部分,它将联系表单信息发送到我的django服务器进行处理。 我不想将联系表单作为模板添加到我的django应用中,因为我使用不同的样式表和资源,并且不希望在服务器之间混用它们。 处理表单数据的视图只是将此数据添加到电子邮件并将其发送到内部电子邮件地址。
我得到一个403 csrf验证失败的错误,因为表单不包含csrf标记。
我现在可以免除接收来自csrf验证请求的视图,但我不确定这会带来哪些安全风险。
我不确定我是否不了解csrf攻击和危险,或者我是否以错误的方式看待这个问题。到目前为止,我所有的搜索和django-csrf相关问题的所有答案都没有帮助我。
这里是我的问题:
- 有没有更好的办法来解决这个问题呢?
- 我可以使用csrf_exempt而不会增加任何安全风险(例如通过执行额外的验证)吗?
答
您可以动态添加CSRF令牌,这是一种用于Ajax请求的技术。从https://docs.djangoproject.com/en/1.11/ref/csrf/:
/**
* getCookie gets a cookie called 'name' in the current session
* @param name name of the cookie to get
* @returns value of the cookie requested, null if not found
*/
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;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
/**
* When doing posts, deletes, etc. we need to transmit the CSRF cookie for
* the request to go through properly, so add the cookie to all ajax calls
* that need the cookie.
*/
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
然后,您可以在“提交”点击表单上通过Ajax调用,然后重定向到下一个页面发布表单数据。
答
我会建议通过这个决定,然后再使用由django提供的csrf_exempt装饰器来从表单中免除csrf验证。
What is a CSRF token ? What is its importance and how does it work?
虽然如今它是一个很好的做法,用户获得更好的安全措施形式csrf_token。