0

I have an angularJS application in which I use Angular's CSRF protection mechanism for all POST, PUT and other nonsafe web service calls. It works well except for one case: a multipart/form-data POST which uploads a file to the server.

In this case, as I am posting a form and file data directly to the web service, the angular $http service is not involved, and therefore does not append the CSRF header to the request in the way that it does with XHR requests.

I have a couple of questions:

  • do I need to protect this POST against CSRF (I imagine I do)
  • can I / how can I get Angular to add the CSRF header to the POST request?
Paul Taylor
  • 5,651
  • 5
  • 44
  • 68

2 Answers2

0

If you uploads a file to the server by means of XHR through jQuery, you can add default header:

$.ajaxSetup({
    headers: {
        "requestVerificationToken": myToken
    }
});
iKBAHT
  • 644
  • 6
  • 17
  • Yes. I can do the same using angular's $http service as well, but I'm using an angular component called ngUpload which uses a form post (inside an IFrame, I believe). – Paul Taylor Dec 05 '13 at 07:57
  • 1
    ngUpload have option ["upload-options-enable-rails-csrf"](https://github.com/twilson63/ngUpload) . It turns on support CSRF by adding a hidden form field with the csrf token. – iKBAHT Dec 05 '13 at 11:13
  • Interesting, I didn't know that was the approach used with that option. It might work. Will investigate. – Paul Taylor Dec 05 '13 at 11:29
0

I decided in the end that as the post was made by a form rather than AJAX, the method should have been in a standard MVC controller rather that a WebAPI one. That way I could use the standard MVC Html.AntiForgeryToken helper on the form and the ValidateAntiForgeryToken attribute on the method.

Paul Taylor
  • 5,651
  • 5
  • 44
  • 68