DP's CODE NOTES

Ajax and CSRF

2019-03-13

Cross-Site Request Forgery (CSRF)   "...is an attack that forces an end user to execute unwanted actions on a web application in which they're currently authenticated."
It is quite easy to forget to handle this vulnerability in general and maybe more so for Ajax endpoints.
If implemented it does not only protect against CSRF but also gives a basic protection from spam bots and other attacks that makes a request directly to the endpoint from another server. Why? Since the attacker would need to first load a token from your site/page and have the correct token cookie set. This makes it a bit harder to attack your site but of course it is not nearly as protective as a captcha implementation.
Lets look at a .NET MVC implementation:

First the attribute class that can be used for different methods:

To protect a method, just decorate the method with this class:

        [System.Web.Mvc.HttpPost]
        [ValidateHeaderAntiForgeryToken]
        public ActionResult Login([FromBody] LoginBody signin)
        {....
        

In your form, just add this which will generate a cookie and hidden value:

     
          @Html.AntiForgeryToken()

        

From the javascript, add a header with the value from the generated token. (This header is needed if json is used, otherwise it could be sent as form data)

        fetch(url, {
          method: 'POST',
          headers: {
          Accept: 'application/json',
          'Content-type': 'application/json',
          __RequestVerificationToken: document.querySelector('input[name="__RequestVerificationToken"]').value,

      }...