Django CSRF Token without forms

后端 未结 4 1252
天命终不由人
天命终不由人 2021-02-05 21:04

Sounds strange but what about the scenario posting contents with Javascript (for example AJAX) without using a form (could be possible to read several contents from the surface)

4条回答
  •  余生分开走
    2021-02-05 22:00

    There are two steps in configuring CSRF token, if you would want to post without a form. Basically get the csrftoken from Cookie, and set the Header with csrftoken (before you POST the data).


    1) Get the csrftoken from Cookie.

    // Function to GET csrftoken from Cookie
    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');
    

    2) Once you have the csrftoken, you should set the Header with csrftoken (before you POST the data).

    function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }
    
    // Function to set Request Header with `CSRFTOKEN`
    function setRequestHeader(){
        $.ajaxSetup({
            beforeSend: function(xhr, settings) {
                if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                }
            }
        });
    }
    
    function postSomeData() {
        .....
        setRequestHeader();
    
        $.ajax({
            dataType: 'json',
            type: 'POST',
            url: "/url-of-some-api/",
            data: data,
            success: function () {
                alert('success');
            },
            error: function () {
                alert('error');
            }
        });
    
    }
    

提交回复
热议问题