In this post, I will tell you about Anti Forgery Tokens with AngularJS and ASP.NET 5. Single Page Applications utilizing AngularJS with ASP.NET by default leave our Web API methods open to forgery abuse. A couple of straightforward steps will permit you to include hostile to phony security. The primary step will be to make a custom activity channel ascribe to test our answer which you can use to finish web programming interface classes or individual activities.

 

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 = 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 following step is to verify ASP.NET includes its standard forgery token cookie and hidden field in the markup. Include the accompanying line into the markup.
@Html.AntiForgeryToken();

Presently, we have to redesign our AngularJS code to pass anti forgery token back in the header with all our web API calls. The most straightforward approach to do this is to situated a default up in the run system for the AngularJS application module, e.g.
.run(function($http) {
    $http.defaults.headers.common['X-XSRF-Token'] =      

angular.element('input[name="__RequestVerificationToken"]').attr('value');
})

HostForLIFE.eu ASP.NET 5 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.