Django - CSRF 验证失败 - 将数据从静态网站上的表单发送到我的 Django 应用程序

Django - CSRF verification failed - send data from form on static website to my django app

我的设置:

我想添加一个联系表单,它是我的静态网站的一部分,它将联系表单信息发送到我的 Django 服务器进行处理。 我不想将联系表单作为模板添加到我的 Django 应用程序中,因为我使用的是不同的样式表和资源,并且不想在服务器之间混合使用它们。 处理表单数据的视图只是将此数据添加到电子邮件并将其发送到内部电子邮件地址。

我收到 403 csrf 验证失败错误,因为表单不包含 csrf 令牌。

我现在可以免除接收请求的视图进行 csrf 验证,但我不确定这会带来哪些安全风险。

我不确定我是否没有理解 csrf 攻击和危险,或者我是否以错误的方式看待这个问题。到目前为止,我所有的搜索和对 django-csrf 相关问题的所有答案都没有帮助我。

这是我的问题:

您可以动态添加 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);
        }
    }
});

然后您可以 'submit' 通过 ajax 调用点击您的表单 post 表单数据,然后重定向到下一页。

我建议在使用 django 提供的 csrf_exempt 装饰器免除表单的 csrf 验证之前先完成此操作并做出决定。

What is a CSRF token ? What is its importance and how does it work?

尽管如今,为了更好的安全措施,用户 csrf_token 的表单是一种很好的做法。