Angular2 ASP.NET Core AntiForgeryToken Angular2 ASP.NET Core AntiForgeryToken angular angular

Angular2 ASP.NET Core AntiForgeryToken


A custom action filter is not necessary. It can all be wired up in Startup.cs.

using Microsoft.AspNetCore.Antiforgery;(...)public void ConfigureServices(IServiceCollection services){  services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");  (...)}public void Configure(IApplicationBuilder app, IAntiforgery antiforgery){  app.Use(next => context =>  {    if (context.Request.Path == "/")    {      //send the request token as a JavaScript-readable cookie, and Angular will use it by default      var tokens = antiforgery.GetAndStoreTokens(context);      context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions { HttpOnly = false });    }    return next(context);  });  (...)}

Then all you need in your controllers is the [ValidateAntiForgeryToken] decorator wherever you want to enforce that a token is provided.

For reference, I found this solution here - AspNet AntiForgery Github Issue 29.


I am using a action filter to send the request tokens.Simply apply it to the actions you want a new antiforgery token, e.g. Angular2 SPA, WebAPI action, etc.

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]public class AngularAntiForgeryTokenAttribute : ActionFilterAttribute{    private const string CookieName = "XSRF-TOKEN";    private readonly IAntiforgery antiforgery;    public AngularAntiForgeryTokenAttribute(IAntiforgery antiforgery)    {        this.antiforgery = antiforgery;    }    public override void OnResultExecuting(ResultExecutingContext context)    {        base.OnResultExecuting(context);        if (!context.Cancel)        {            var tokens = antiforgery.GetAndStoreTokens(context.HttpContext);            context.HttpContext.Response.Cookies.Append(                CookieName,                tokens.RequestToken,                new CookieOptions { HttpOnly = false });        }    }}
/* HomeController */[ServiceFilter(typeof(AngularAntiForgeryTokenAttribute), IsReusable = true)]public IActionResult Index(){    return View();}/* AccountController */[HttpPost()][AllowAnonymous][ValidateAntiForgeryToken]// Send new antiforgery token[ServiceFilter(typeof(AngularAntiForgeryTokenAttribute), IsReusable = true)]public async Task<IActionResult> Register([FromBody] RegisterViewModel model){    //...    return Json(new { }); }

Register the attribute in Startup, and configure Antiforgery service to read the request token form "X-XSRF-TOKEN" header.

public class Startup{    // ...    public void ConfigureServices(IServiceCollection services)    {        // ...        services.AddScoped<AngularAntiForgeryTokenAttribute>();        services.AddAntiforgery(options =>        {            options.HeaderName = "X-XSRF-TOKEN";        });    }}


I think you need to make custom AntiForgeryValidationToken attribute that supports sending token via header instead of form values. Then add token to header of every request from your Angular2 app to your api. Example here How do you set global custom headers in Angular2?