Search code examples
jquerydjangocsrfdjango-csrf

jQuery POST using Django CSRF - Remove X-CSRFToken Header After?


I'm following the instructions here. And the Django folks say to run this before my Ajax post request to include the CSRF token.

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);
        }
    }
});

This works but do I need to remove that token from the headers after my POST? I don't want all jQuery post requests including it because I figure it could leak the token.

So how do I undo the ajax setup after running the POST?

And do I need to do this?


Solution

  • I don't think you need to, as it checks that it's not a cross-domain request before adding the header.