django中使用form表单或者ajax提交数据时如何验证csrftoken

发布时间 2023-07-05 17:09:02作者: 等日落
  • 使用form表单来提交数据时,如何验证csrftoken

image

  • ajax提交数据时验证csrftoken

在需要提交的html页面引入以下js文件就行

引入csrf.js文件

<script src="{% static 'js/csrf.js' %}"></script>

文件内容:

/**
 * 根据cookie的name获取对应的值
 * @param name
 * @returns {null}
 */
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            // 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;
}

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}

$.ajaxSetup({
    beforeSend: function (xhr, settings) {
        if (!csrfSafeMethod(settings.type)) {
            xhr.setRequestHeader("X-CSRFTOKEN", getCookie('csrftoken'));
        }
    }
})