0

I set up an ajax prefilter for CSRF protection.. This uses the MVC @Html.AntiForgeryToken() and automatically appends it to each .ajax request.

    $.ajaxPrefilter(function (options, originalOptions, jqXHR) {
        if (options.type.toUpperCase() === "POST") {
            // We need to add the verificationToken to all POSTs
            var token = $("input[name^=__RequestVerificationToken]").first();
            if (!token.length) return;

            var tokenName = token.attr("name");

            // If the data is JSON, then we need to put the token in the QueryString:
            if (options.contentType.indexOf('application/json') === 0) {
                // Add the token to the URL, because we can't add it to the JSON data:
                options.url += ((options.url.indexOf("?") === -1) ? "?" : "&") + token.serialize();
            } else if (typeof options.data === 'string' && options.data.indexOf(tokenName) === -1) {
                // Append to the data string:
                options.data += (options.data ? "&" : "") + token.serialize();
            }
        }
    });

now, I need to do the same thing for angular $http requests but am seriously struggling. Any tips?

user3689167
  • 863
  • 1
  • 14
  • 28
  • what you tried so far? – Pankaj Parkar Oct 07 '15 at 18:20
  • That looks like an interceptor. Check the $http documentation. https://docs.angularjs.org/api/ng/service/$http#interceptors – toskv Oct 07 '15 at 18:29
  • AngularJS does this out of the box. No need to implement your own interceptor https://docs.angularjs.org/api/ng/service/$http look for Cross Site Request Forgery (XSRF) Protection – masimplo Oct 07 '15 at 18:32

1 Answers1

0

Something like this from one of my previous answers?

How to send csrf_token() inside AngularJS form using Laravel API?

var xhReq = new XMLHttpRequest();
xhReq.open("GET", "//" + window.location.hostname + "/api/csrf", true);

xhReq.onload = function(e) {
  if (xhReq.readyState === 4) {
    if (xhReq.status === 200) {
      app.constant("CSRF_TOKEN", xhReq.responseText);

      app.run(['$http', 'CSRF_TOKEN', function($http, CSRF_TOKEN) {
        $http.defaults.headers.common['X-Csrf-Token'] = CSRF_TOKEN;
      }]);
    }
  }
};

xhReq.send(null);
Community
  • 1
  • 1
Gravy
  • 12,264
  • 26
  • 124
  • 193