Friday, March 20, 2015

CSRF in AngularJS/Web API on Web Forms (ng-resource)

I came across an interesting site configuration where there was need of anti forgery tokens (due to Cross-Site Request Forgery exploits), however it was a web forms implementation and AngularJS was making Web API calls via $resource (both GET and POST).

The code on the master page (or can be placed on the form) is what puts the hidden field containing the token on the page. The ActionFilterAttribute is defined as "AntiForgeryTokenAttribute", but on the Web API side the Attribute is dropped and it is simply "[AntiForgeryToken]".

On the AngularJS side, the $resource POST request adds in the header "X-XSRF-Token", which connects with the hidden field on the master page (or layout). I place it here instead of in the form in case there are multiple forms on the same page that require anti forgery tokens.

The action filter attribute was taken from GeeksWithBlogs.

1 comment:

  1. AntiForgery.GetHtml() will require <%@ Import Namespace="System.Web.Helpers" %>