Anti Forgery Tokens with AngularJS and ASP.NET Web API

Single Page Applications using AngularJS with ASP.NET will by default leave our web api methods open to forgery abuse. A few simple steps will allow you to add anti forgery protection.

The first step will be to create a custom action filter attribute to test our solution which you can use to decorate web api classes or individual actions. Here is the code...

using System; using System.Linq; using System.Net.Http; using System.Web.Helpers; using System.Web.Http.Filters;

namespace antiforgery { public sealed class ValidateCustomAntiForgeryTokenAttribute : ActionFilterAttribute { public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext) { if (actionContext == null) { throw new ArgumentNullException("actionContext"); } var headers = actionContext.Request.Headers; var cookie = headers .GetCookies() .Select(c => c[AntiForgeryConfig.CookieName]) .FirstOrDefault(); var tokenFromHeader = ""; if (headers.Contains("X-XSRF-Token")) tokenFromHeader = headers.GetValues("X-XSRF-Token").FirstOrDefault(); AntiForgery.Validate(cookie != null ? cookie.Value : null, tokenFromHeader);

        base.OnActionExecuting(actionContext);
    }
}

}

The web api classes or methods will need decorating appropriately to ensure this code is run, i.e.

[ValidateCustomAntiForgeryTokenAttribute]

The next step is to make sure ASP.NET includes its standard anti forgery token cookie and hidden field in the markup. Add the following line into the markup...

@Html.AntiForgeryToken();

And finally, we need to update our AngularJS code to pass the anti forgery token back in the header with all our web api calls. The easiest way to do this is to set a default up in the run method for the AngularJS application module, e.g.

.run(function($http) { $http.defaults.headers.common['X-XSRF-Token'] = angular.element('input[name="__RequestVerificationToken"]').attr('value'); })

This article is part of the GWB Archives. Original Author: Frez

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.