我的设置:
我想添加一个联系人表单,这是我的静态网站的一部分,并将联系人表单信息发送到我的django服务器进行处理。我不想将联系人表单作为模板添加到我的django应用程序中,因为我使用的是不同的样式表和资源,并且不想在服务器之间混合它们。处理表单数据的视图只是将这些数据添加到电子邮件中并将其发送到内部电子邮件地址。
我得到一个403 csrf验证失败的错误,因为表单不包括csrf令牌。
我现在可以免除收到csrf核查请求的意见,但我不确定这会造成何种安全风险。
我不确定我是否不理解csrf的攻击和危险,或者我是否以错误的方式看待这个问题。到目前为止,我对django-csrf相关问题的所有搜索和回答都没有帮助我。
以下是我的问题:
发布于 2017-10-20 14:20:17
您可以动态添加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调用发布表单数据,然后重定向到下一页。
发布于 2017-10-20 16:54:56
我建议在您使用django提供的csrf_exempt装饰器来避免csrf验证不受表单影响之前,先考虑一下这一点。
What is a CSRF token ? What is its importance and how does it work?
尽管现在,为了更好的安全措施,在表单中使用csrf_token是一种很好的做法。
https://stackoverflow.com/questions/46850937
复制相似问题