Access Denied Error when using XHR PUT and DELETE

Posted by Tejus Parikh on February 8, 2012

Late one night, I was attempting to wire up a delete button on a Rails app using XHR. However, every time I attempted to make the XHR call, I saw AccessDenied in the server log and my session was un authenticated. Since it was late, I remapped it to a different URL and moved on.

However, the fact that this did not work still bothered me and when I revisited it after a good night's sleep, the answer was quite obvious. My Ajax setup (copied from many Rails projects ago) looked like:

$("body").bind("ajaxSend", function(elm, xhr, s){
    if (s.type == "POST") {
        xhr.setRequestHeader('X-CSRF-Token', Common.CSRF_TOKEN);
    }
});

I was only setting the X-CSRF-Token on a POST. Therefore, when the server received the DELETE verb, it killed the session, thinking that something was afoul.

Changing that line to:

$("body").bind("ajaxSend", function(elm, xhr, s){
    if (s.type == "POST" || type == "DELETE" || type == "PUT") {
        xhr.setRequestHeader('X-CSRF-Token', Common.CSRF_TOKEN);
    }
});

fixed the issue in the correct way.

Tejus Parikh

I'm a software engineer that writes occasionally about building software, software culture, and tech adjacent hobbies. If you want to get in touch, send me an email at [my_first_name]@tejusparikh.com.