Angular JS and Web API Part 2: Anti-Forgery

Typically you only want to add Anti-Forgery tokens to POST requests for Authenticated users as a security measure. Here’s the steps to get this going:

On your ASP.NET webpage (e.g. a .master file) add the following code to insert a input field for the Antiforgery token:

It’s important to note that MVC and Web API both have their own implementation of AntiForgery, so make sure you have the right DLL referenced and the Import namespace specified above.

Here is an Attribute you can add to your Web API endpoints to handle the token passed in:

Now to pass the token from Angular JS you need to add the following to the request headers of your $resource powered request.

‘post’: { method: 'POST’, headers: { 'X-XSRF-Token’: angular.element('input[name=“__RequestVerificationToken”]’).attr('value’) } }

I’ve simplified this by using a boolen parameter to specify whether to add this, see the services.js in Part 1.