Validate Anti-Forgery Token using AngularJS, TypeScript, ASP.NET MVC and Web API

I’ve used Olav Nybø’s guide as a base for this article.

AngularJS Directive

module AngularApp {  
  "use strict";

  export function antiForgeryToken($http: ng.IHttpService): ng.IDirective {
    return (scope, element, attrs) => {
      $http.defaults.headers.common['RequestVerificationToken'] = attrs.antiForgeryToken || "no request verification token";

  antiForgeryToken.$inject = ['$http'];

MVC Html helper method

public static class AntiForgeryExtension {  
    public static string RequestVerificationToken(this HtmlHelper helper) {
      return String.Format("anti-forgery-token={0}", GetTokenHeaderValue());

    private static string GetTokenHeaderValue() {
      string cookieToken, formToken;
      System.Web.Helpers.AntiForgery.GetTokens(null, out cookieToken, out formToken);
      return cookieToken + ":" + formToken;

Print directive with generated anti-forgery token to your view

<form id="registration" @Html.RequestVerificationToken()>  

Web API validate attribute

ATTN! Be sure to use System.Web.Http.Filters.ActionFilterAttribute, not System.Web.Mvc.ActionFilterAttribute!

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

namespace MyNamespace {  
  public class ValidateAntiForgeryAngular : ActionFilterAttribute {
    public override void OnActionExecuting(HttpActionContext filterContext) {
      var headers = filterContext.Request.Headers;
      string cookieToken = null;
      string formToken = null;
      var rvt = headers.GetValues("RequestVerificationToken").FirstOrDefault();
      if(rvt != null) {
        string[] tokens = rvt.Split(':');
        if(tokens.Length == 2) {
          cookieToken = tokens[0].Trim();
          formToken = tokens[1].Trim();
      AntiForgery.Validate(cookieToken, formToken);

Web API method

public void PostSomething(MySomething something)  
    //some code here


Just add this somewhere in your template @Html.RequestVerificationToken() and the action filter attribute [ValidateAntiForgeryAngular] above your Web API method.


Leave a Reply

Your email address will not be published. Required fields are marked *