Search code examples
ajaxdjangoprototypejsscriptaculouscsrf

Protecting prototype.js based XHR requests against CSRF


Django has been updated to 1.3, and in fact ever since 1.2.5, it has extended the scheme to pass a Cross Site Request Forgery protection token to XMLHttpRequests. The Django folks helpfully provide an example for jQuery to apply a specific header to every XHR.

Prototype (and thus Scriptaculous) have to comply to this scheme, yet I can't find a way to tell prototype to add the X-CSRFToken header. The best would be to do it once in a way that applies it across the app (like for jQuery).

Is there a way to do that?


Solution

  • This is a wild guess but you could try extending the base AJAX class...

    Ajax.Base.prototype.initialize = Ajax.Base.prototype.initialize.wrap(
        function (callOriginal, options) {
            var headers = options.requestHeaders || {};
            headers["X-CSRFToken"] = getCookie("csrftoken");
            options.requestHeaders = headers;
            return callOriginal(options);
        }
    );