Preventing CSRF Attacks Using ASP.NET Core, JavaScript And Angular


Today, we will learn about Cross-Site Request Forgery attacks and how to prevent them in ASP.NET Core, JavaScript, and Angular.


Cross-Site Request Forgery, also known as CSRF (pronounced as “See-Surf”), XSRF, One-Click Attack, and Session Riding, is a type of attack where the attacker forces the user to execute unwanted actions in an application that the user is logged in. The attacker tricks the user into performing actions on their behalf. The impact of this attack depends on the level of permissions that the user has. For example, in a vulnerable bank website, the attacker could transfer an amount of money from the victim’s account or take ownership of the whole account.
Source code
The source code for the samples of this article is available on GitHub at the following link.
You have five projects in the repository,
  • The attack sample projects, AttackSample.AttackerApp and AttackSample.VulnerableApp shows a valid CSRF attack to a vulnerable app.
  • The secure sample project, SecureSample.SecureApp and SecureSample.AttackerApp shows a failed CSRF attack to a protected app.
  • The Angular project, SecureSample.AngularApp, which stands on its own.

CSRF Example

If we take the bank website example, the attacker may trick the user into loading some website or link that contains a script that makes a forged request to the bank website to transfer some funds. If the user is currently logged on to the bank website, and the website is vulnerable to such attacks, the attacker may succeed.
For example, if the bank website allows the following request for transfers,
  1. GET  
The attacker could plug his bank account number into the “to” field and sends the user to a page that has a script that makes the above request or encourages him/her into clicking a certain link, for example,
  1. <a href="">Read More!</a>  
Or embeds the request into a fake 0x0 image,
  1. <img src="" width="0" height="0" />  
The attacker could include his code in a site that the user usually visits (e.g., putting a link into some download forums), or distribute his page with some help of social engineering such as sending a link via email or chat.
If the user is already logged on to the bank account, when he/she opens the page or clicks the fake link, the browser will automatically include target website cookies and other data and performs the forged request, results in a successful transfer request.

Anatomy of an Attack

To summarize, a successfully CSRF attack consists of,
  • A vulnerable website.
  • A user who is currently logged on to that website.
  • Session and other user cookies that the browser may include in requests.
  • Easy-to-predict request parameter.
  • User visits a harmful page or clicks on a fake link that executes a forged request to the vulnerable website.

Protecting Your Web Application

To protect your web application against such attacks, always,
  • Use unpredictable parameters. Make it difficult for an attacker to simulate or construct a request to your application. An example of unpredictable parameters of the use of tokens, which are going to be explained soon.
  • Strictly validate in every case and in every step.

CSRF Attacks in Action

In our code sample, we have two AttackSample projects, one is for the vulnerable app, and the other is for the attacker app. In the vulnerable app, the user is authenticated, and a cookie is created to save user data,
  1. [HttpGet]  
  2. public bool IsAuthenticated()  
  3. {  
  4.   return Context.Request.Cookies["IsAuthenticated"] == "1";  
  5. }  
  7. [HttpPost]  
  8. public IActionResult Login()  
  9. {  
  10.   Context.Response.Cookies.Append("IsAuthenticated""1");  
  11.   return RedirectToAction(nameof(Index), "Home");  
  12. }  
  14. [HttpPost]  
  15. public IActionResult Logout()  
  16. {  
  17.   Context.Response.Cookies.Delete("IsAuthenticated");  
  18.   return RedirectToAction(nameof(Index), "Home");  
  19. }  
The application maintains a balance object and allows easy-to-predict requests for debit and credit operations,
  1. [HttpGet]  
  2. public int Balance()  
  3. {  
  4.   return CurrentBalance;  
  5. }  
  7. [HttpPost]  
  8. public int Debit(int amount)  
  9. {  
  10.   CurrentBalance -= amount;  
  11.   return Balance();  
  12. }  
  14. [HttpPost]  
  15. public int Credit(int amount)  
  16. {  
  17.   CurrentBalance += amount;  
  18.   return Balance();  
  19. }  
On the other hand, the attacker tricks the user into executing the fake request by promising him with a gift when he clicks the link,
  1. <form method="post" action="http://localhost:62833/api/Debit">    
  2.   <input type="hidden" name="amount" value="50" />    
  3.   <button type="submit">Click here to win a free iPhone!</button>    
  4. </form>    
The user is tricked into executing the fake request and resulting in a successful amount transfer.

Anti-Forgery Tokens

The key to protecting your website against those kinds of attacks, is by using unpredictable request parameters. One of those unpredictable parameters is the anti-forgery tokens.
An anti-forgery token, also called CSRF token, is a unique, secret, unpredictable parameter generated by a server-side application for a subsequent HTTP request made by the client. When that request is made, the server validates this parameter against the expected value and rejects the request if the token is missing or invalid.
So, basically, the following request,
  1. GET  
Will be extended with a third argument:

  1. GET  
That token is huge and impossible-to-guess. The server will include that token for the subsequent request only and will generate a new one each time a page/form is served.
Technically speaking, the anti-forgery token is not an argument that is being sent in the query string. In fact, it is a cookie represented as hidden field that you generate inside your form. When the form is submitted, this value will be included along with the request as a header. The server code will check request and validate the value sent from client.

Anti-Forgery in ASP.NET Core

By default, the new ASP.NET Core Razor engine will include an anti-forgery token for the page forms, and all you need is to add the corresponding validation. Despite this, the next few sections will let you know how to generate the anti-forgery tokens in your app and how to validate them.

Token Generation: The Manual Way

There are two ways to generate and validate anti-forgery tokens, we will start by the manual, uncomfortable way. This can be done by using the IAntiForgery service.
  1. @inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Csrf  
  2. @functions {  
  3.   public string GenerateCsrfToken()  
  4.   {  
  5.     return Csrf.GetAndStoreTokens(Context).RequestToken;  
  6.   }  
  7. }  
  1. <form method="post">  
  2.   <input type="hidden" id="RequestVerificationToken" name="RequestVerificationToken" value="@GenerateCsrfToken()" />  
  3. </form>   
The GetAndStoreTokens method generates a request token and stores the token in a response cookie. You get access to the generated token using the RequestToken property.
The generated hidden field will be like the following (the token has been abbreviated for clarity), 
  1. <input type="hidden" id="RequestVerificationToken" name="RequestVerificationToken" value="CfDJ8El14QZHDe5Dtl0m3qOu6_PbEHcKAJ5ZjSRj6iF...">  
Another, clearer way, for manually generating CSRF tokens is by using the MVC HTML helper,
  1. <form method="post">  
  2.   @Html.AntiForgeryToken()  
  3. </form>  
You can check the generated cookie using Chrome DevTools,

Token Generation: The Automatic Way

As we said earlier, the new ASP.NET Core Razor engine will always generate CSRF tokens for you, however, you still have the control over the token generation process.
You can customize the token generation process for Razor pages using the AddAntiforgery method which can be called in your Startup.ConfigureServices method.
  1. services.AddAntiforgery(options =>  
  2. {  
  3.   options.FormFieldName = "AntiForgeryFieldName";  
  4.   options.HeaderName = "AntiForgeryHeaderName";  
  5.   options.Cookie.Name = "AntiForgeryCookieName";  
  6. });  
The previous code will generate a hidden field for the token with the specified name, and the token will be sent along with the request with the specified header name.
  1. <input name="AntiForgeryFieldName" type="hidden" value="CfDJ8N1DZWaKEuhDio...">  
By default, the generated cookie name in ASP.NET core is “.AspNetCore.Antiforgery.<hash>”, the field name is “__RequestVerificationToken”, and the header name is “RequestVerificationToken”.

Token Validation

Now comes the next step, the token validation. Let us start by the normal, uncomfortable way. In your target action, you may use the following code for token validation:
  1. private Microsoft.AspNetCore.Antiforgery.IAntiforgery Csrf { getset; }  
  2. public ApiController(Microsoft.AspNetCore.Antiforgery.IAntiforgery csrf)  
  3. {  
  4.   this.Csrf = csrf;  
  5. }  
  7. private async Task<bool> ValidateAntiForgeryToken()  
  8. {  
  9.   try  
  10.   {  
  11.     await Csrf.ValidateRequestAsync(this.HttpContext);  
  12.     return true;  
  13.   }  
  14.   catch (Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException)  
  15.   {  
  16.     return false;  
  17.   }  
  18. }  
  21. [HttpPost]  
  22. public async Task<ActionResult<int>> Debit(int amount)  
  23. {  
  24.   if (false == await ValidateAntiForgeryToken())  
  25.     return BadRequest();  
  27.   // action logic here  
  28. }   
In the previous code, we started by defining our IAntiforgery service. This service allows you to validate a given request using the ValidateRequestAsync method which throws AntiforgeryValidationException exception when the token is invalid. We called this function the first thing in our Debit method and returned a 400 Bad Request response for invalid tokens.
Another, clearer way, to validate a CSRF token is by using the ValidateAntiForgeryToken attribute,
  1. [HttpPost]  
  2. [ValidateAntiForgeryToken]  
  3. public async Task<ActionResult<int>> Debit(int amount)  
The above code will perform the same functionality as the manual IAntiforgery service code.
Now, when we run our application, we can see the difference. The app has been protected against CSRF attacks and the attacker cannot perform a request to your app.
Worth mentioning that ValidateAntiForgeryToken can be applied to the controller class and will cause CSRF validation on all endpoints. We also have some alternatives to using ValidateAntiForgeryToken attribute,
  • AutoValidateAntiForgeryToken attribute: Will automatically validate endpoints for all HTTP methods except GET, HEAD, OPTIONS and TRACE.
  • IgnoreAntiforgeryToken attribute: Will ignore a method from validation if the parent class is decorated with ValidateantiForgeriyToken or AutoValidateAntiForgeryToken.

Anti-Forgery in JavaScript

Let us take another example. Assume that you are accessing your API using JavaScript and you use the following code to call the credit method,
  1. function request(url) {  
  2.   let url = location.origin + "/api/credit?amount=10";  
  4.   var request = {};  
  5.   request.url = url;  
  6.   request.type = 'POST';  
  7.   request.success = function (balance) {  
  8.     $('#balance')[0].innerText = balance;  
  9.   };  
  10.   request.error = function (xhr) {  
  11.     alert(`${xhr.status} ${xhr.statusText}`);  
  12.   };  
  14.   $.ajax(request);  
  15. }  
When the anti-forgery validation is in action, you will receive a 400 bad request error, and this is expected because the ASP.NET Core engine cannot find the CSRF token header.
For this to work, we must add our CSRF token manually to our request headers list. A small change in our code will do the trick,
  1. function request(url) {  
  2.   let url = location.origin + "/api/debit?amount=10";  
  4.   var request = {};  
  5.   request.url = url;  
  6.   request.type = 'POST';  
  7.   request.headers = {  
  8.     'RequestVerificationToken': $('input[name="__RequestVerificationToken"]').val()  
  9.   };  
  10.   request.success = function (balance) {  
  11.     $('#balance')[0].innerText = balance;  
  12.   };  
  13.   request.error = function (xhr) {  
  14.     alert(`${xhr.status} ${xhr.statusText}`);  
  15.   };  
  17.   $.ajax(request);  
  18. }  
As we said before, the default header name for CSRF tokens is “RequestVerificationToken”. If you, for any reason, changed the default header name,
  1. services.AddAntiforgery(options =>  
  2. {  
  3.   options.HeaderName = "AntiForgeryHeaderName";  
  4. });  
Then you will have to change the value in your JavaScript code,
  1. request.headers = {  
  2.   'AntiForgeryHeaderName': $('input[name="__RequestVerificationToken"]').val()  
  3. }; 

Anti-Forgery in Angular

Normally, when accessing a CSRF-protected endpoint from an Angular app, you will receive 400 bad request if you did not specify the CSRF header.
To handle this, you must know the following,
  • Angular will recognize a CSRF token only if it is stored as a cookie under Angular’s dedicated name, which is “XSRF-TOKEN”.
  • Angular will always send the cookie token as a header under the dedicated name “X-XSRF-TOKEN”.
  • Your app must be able to generate the CSRF cookie under Angular’s dedicated name and to validate the CSRF header also under Angular’s dedicated name.
Let us see how we do this,
  1. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IAntiforgery antiforgery)  
  2. {  
  3.   app.Use((context, next) =>  
  4.   {  
  5.     // return current accessed path  
  6.     string path = context.Request.Path.Value;  
  8.     if (path.IndexOf("/api/", StringComparison.OrdinalIgnoreCase) != -1)  
  9.     {  
  10.       var tokens = antiforgery.GetAndStoreTokens(context);  
  11.       context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken,  
  12.         new CookieOptions() { HttpOnly = false });  
  13.     }  
  15.     return next();  
  16.   });  
  17. }  
The code is fairly easy, it does the following,
  • It starts by defining a middleware that will be executed for each request. This middleware will be responsible for generating the CSRF cookie with the dedicated name.
  • In this middleware, it checks the requested path. You do not need to generate the cookie for all requests, you need only for the API-targeted requests. Technical speaking, you need to generate this cookie for requests that targets our API controller, “/api/
  • Next, the code uses the IAntiforgery service to generate and store CSRF token in a cookie using the GetAndStoreTokens method. We used this mechanism before in the manual token generation section. Unless you change the default cookie name using AddForgery method (mentioned earlier,) the default name for the generated token will start with “.AspNetCore.Antiforgery” as we said earlier.
  • Finally, the code reads the generated token and stores it in a cookie for the going request. It uses the dedicated Angular cookie name, “XSRF-TOKEN”.
The next step is to configure the generated the app to read the correct header. As we said earlier, we must preserve the default Angular CSRF header name, “X-XSRF-TOKEN”.
  1. services.AddAntiforgery(opts =>  
  2. {  
  3.   opts.HeaderName = "X-XSRF-TOKEN";  
  4. });  
Now, run the app and see the charm. We are no longer receiving the 400 bad request error. And when investigating the request using Chrome DevTools or Fiddler, we can clearly see the generated cookie and header name.

Angular Absolute Paths Issue

The above code will work like charm if the requested path is relative,
  1. debit(amount: number): Observable<number> {  
  2.   // relative path  
  3.   let url = `/api/debit?amount=${amount}`;  
  4.   return this.request(url);  
  5. }  
  7. request(url: string): Observable<number> {  
  8.   let result: number;  
  9.   return<number>(url, { });  
  10. }  
However, when the requested path is absolute, even if it is same host, Angular is not smart enough to include the CSRF token in the request. You have to manually include it in your request. The following code, for example, will not work,
  1. credit(amount: number): Observable<number> {  
  2.   // absolute path  
  3.   let url = this.baseUrl + `api/credit?amount=${amount}`;  
  4.   return this.request(url);  
  5. }  
The solution to such case is to add the header manually to the request, or to use an HTTP interceptor to automatically add it to all requests. Let us see how to define our interceptor. We will start by the interceptor class itself.
  1. import { Injectable } from "@angular/core";  
  2. import { HttpInterceptor, HttpXsrfTokenExtractor } from "@angular/common/http";  
  3. import { HttpEvent, HttpHandler, HttpRequest } from "@angular/common/http";  
  4. import { Observable } from "rxjs";  
  7. @Injectable()  
  8. export class XsrfInterceptor implements HttpInterceptor {  
  9.   constructor(private xsrfTokenExtractor: HttpXsrfTokenExtractor) {  
  10.   }  
  12.   intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {  
  13.     // load token  
  14.     let xsrfToken = this.xsrfTokenExtractor.getToken();  
  16.     if (xsrfToken != null) {  
  17.       // create a copy of the request and  
  18.       // append the XSRF token to the headers list  
  19.       const authorizedRequest = req.clone({  
  20.         withCredentials: true,  
  21.         headers: req.headers.set('X-XSRF-TOKEN', xsrfToken)  
  22.       });  
  24.       return next.handle(authorizedRequest);  
  25.     } else {  
  26.       Return next.handle(req);  
  27.     }  
  28.   }  
  29. }  
The above code simply extracts the token using the HttpXsrfTokenExtractor service which handles the token extraction from the cookie. It then copies the current request and appends the CSRF header using the dedicated name, “X-XSRF-TOKEN”. It finally, passes the request through the pipe to the next handler.
To be to use the HttpXsrfTokenExtractor service, you need to include its module in the app imports.
  1. imports: [  
  2.   HttpClientModule,  
  3. ],  
Finally, you must include your interceptor in the injectable objects of the application.
  1. providers: [    
  2.   { provide: HTTP_INTERCEPTORS, useClass: XsrfInterceptor, multi: true }    
  3. ],    
Now you can run the application and see how it operates smoothly for all requests.
Worth mentioning, that if your Angular app is contained inside a Razor CSHTML file, you can simply generate the CSRF token using the regular way,
  1. <div>    
  2.     <app-root></app-root>    
  3.     @Html.AntiForgeryToken()    
  4. </div>     
And in the Angular code, you can use the jQuery-style to get the value of the token and include it in your request using code like this,
  1. declare var $: any;    
  3. const httpOptions = {    
  4.     headers: new HttpHeaders({    
  5.       'X-XSRF-Token': $('input[name=__RequestVerificationToken]').val()    
  6.     })    
  7.   };    
  8., httpOptions);    


By the end of this article, I think you have full knowledge of how CSRF attacks work and how to protect your app from those attacks.
Again, the source code for the samples is available on GitHub at the following link.
You have five projects in the repository,
  • The attack sample projects, AttackSample.AttackerApp and AttackSample.VulnerableApp which show a valid CSRF attack to a vulnerable app.
  • The secure sample projects, SecureSample.SecureApp and SecureSample.AttackerApp which show a failed CSRF attack to a protected app.
  • The Angular project, SecureSample.AngularApp, which stands at its own.