django文档中介绍的处理ajax post时,头中添加csrf token的方法

https://docs.djangoproject.com/en/2.0/ref/csrf/#ajax


AJAX

While the above method can be used for AJAX POST requests, it has someinconveniences: you have to remember to pass the CSRF token in as POST data withevery POST request. For this reason, there is an alternative method: on eachXMLHttpRequest, set a custom X-CSRFToken header to the value of the CSRFtoken. This is often easier, because many JavaScript frameworks provide hooksthat allow headers to be set on every request.

上面的方法在每个post时,都要将CSRF token作为post数据来传,不方便,可以设置一个值为CSRFtoken的X-CSRFToken头,这样就能一劳永逸。

Acquiring the token is straightforward:

// using jQuery
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');

如果嫌上述函数实现复杂,可以试试下面的实现,区别是,需要引入

JavaScript Cookie:

<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>

The above code could be simplified by using the JavaScript Cookie library to replace getCookie:

var csrftoken = Cookies.get('csrftoken');



以下描述的是:给ajax设置一个头的X-CSRFToken属性,这样每次发起post时,这个X-CSRFToken属性会自动加入post的信息中。

仔细看,可以猜到:beforeSend: function是一个类似callback的函数,每当post发起时,执行这个函数。函数里的if还做了判断,如果不是同一个域的请求,就不发送csrftoken。

Setting the token on the AJAX request

Finally, you’ll have to actually set the header on your AJAX request, whileprotecting the CSRF token from being sent to other domains usingsettings.crossDomain in jQuery 1.5.1and newer:

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) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});




说明文档中还介绍了另外一种取csrftoken的方法:将csrftoken明文写入网页,在通过jquery取csrftoken值。

Acquiring the token if CSRF_USE_SESSIONS is True

If you activate CSRF_USE_SESSIONS, you must include the CSRF tokenin your HTML and read the token from the DOM with JavaScript:

{% csrf_token %}
<script type="text/javascript">
// using jQuery
var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();
</script>

这里说的是:如果if CSRF_USE_SESSIONS is True,可以直接从html页面读取token的值。而且方法非常简单。(满足一般情况)



猜你喜欢

转载自blog.csdn.net/qq_27361945/article/details/80279768