Django CSRF check failing with an Ajax POST request

前端 未结 22 1419
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 03:46

I could use some help complying with Django\'s CSRF protection mechanism via my AJAX post. I\'ve followed the directions here:

http://docs.djangoproject.com/en/dev/r

22条回答
  •  感情败类
    2020-11-22 03:53

    I have a solution. in my JS I have two functions. First to get Cookies (ie. csrftoken):

    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;
    

    }

    Second one is my ajax function. in this case it's for login and in fact doesn't return any thing, just pass values to set a session:

    function LoginAjax() {
    
    
        //get scrftoken:
        const csrftoken = getCookie('csrftoken');
    
        var req = new XMLHttpRequest();
        var userName = document.getElementById("Login-Username");
        var password = document.getElementById("Login-Password");
    
        req.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {            
                //read response loggedIn JSON show me if user logged in or not
                var respond = JSON.parse(this.responseText);            
                alert(respond.loggedIn);
    
            }
        }
    
        req.open("POST", "login", true);
    
        //following header set scrftoken to resolve problem
        req.setRequestHeader('X-CSRFToken', csrftoken);
    
        req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        req.send("UserName=" + userName.value + "&Password=" + password.value);
    }
    

提交回复
热议问题