Angular, C#, Web

Secure your Angular/ASP.NET Core application with Anti-forgery token

Security has always been at the forefront of Web Applications. There are so many security concerns one has to think of when developing web applications. Today, I want to share with you guys how to secure a Single Page Application (SPA) from Cross-site request forgery (CSRF or XSRF) using Angular 4. If you’re still using Angular 2 this works as well but I recommend upgrading to 4. It’s easy and they made the code faster and smaller (maybe a topic for another day ;-])

By default, the Angular core HTTP library will look for a token in the cookie with the name XSRF-TOKEN and add it to the request. Thanks to the CookieXSRFStrategy provided by Angular, Angular does that part for you. However, you may wish to use another cookie name other than the one provided by default (XSRF-TOKEN). Do do that, Angular documents the steps to provide such override. If you wish to do that, you can create a new CookieXSRFStrategy or create a class. Add it to your providers and the rest will be magic! If this is the route you want to use, I suggest reading the documentation.

On the ASP.NET Core side, you need to push the Anti-forgery token to a cookie with the name specified above. To do that you need to create a middleware that will be able to append it to your SPA. Here’s a class implementing the middleware along with the method extension to be able to use it:

Once you have your middleware created, you need to add it to the pipeline. In your Startup class, in the Configure method, add the following line before the UseMVC method:

app.UseAntiforgeryToken();

If you’re following properly, you must have realized that you need to tell the Antiforgery module of ASP.NET Core what to look for the token when validating. To do that, in the ConfigureServices method, add the following:

services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");

If you add the module but don’t setup the HeaderName option, it will use form data by default.

Voilà! Now the Anti-forgery token is added to your application. Ok that’s great, but how can I make sure I’m protected?

To use it, decorate your action methods or controllers with the ValidateAntiForgeryToken attribute. As simple as that.