XSRF or CSRF with Angular and Dot Net Core Web API

Turns out adding XSRF, CSRF, See-Surf or whatever the name we call it now to an Angular app with a .NET Core Web API is really really easy.

Angular is set up by convention to expect a cookie with the name XSRF-TOKEN.

The $http service in Angular will by default read the value of this cookie and add it to a header called X-XSRF-TOKEN for use on every subsequent request.

The only changes required are on the Web API side.

  1. First set the XSRF-TOKEN cookie when the user makes a request to the root path of your API:
public void Configure(IApplicationBuilder app, IAntiforgery antiforgery)
{
    app.Use(next => context =>
    {
        string path = context.Request.Path.Value;

        if (
            string.Equals(path, "/", StringComparison.OrdinalIgnoreCase))
        {
            var tokens = antiforgery.GetAndStoreTokens(context);
            context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, 
                new CookieOptions() { HttpOnly = false });
        }

        return next(context);
    });
}
  1. Then configure the antiforgery service to look for a header named X-XSRF-TOKEN:
public void ConfigureServices(IServiceCollection services)
{
    services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
}
  1. Finally add the following filter to any action that you want to protect from XSRF:
[ValidateAntiForgeryToken]

And voila your Angular app is now secure from XSRF attacks. Easy as un, deux, trois.

For a working demo check out [this GitHub repo] (https://github.com/fiyazbinhasan/Antiforgery)

comments powered by Disqus