Using AntiforgeryToken in AJAX Calls

We are on the last leg of a project and one of the remaining tasks is to apply Cross-Site Request Forgery (CSRF) measures to all possible attack surface of the website. We normally use Google’s Captcha for this, however, this is not ideal on all scenarios. For one, adding Captcha to all forms would drive your users mad. For scenarios that require non-disruptive measure, we use ASP.NET’s built-in method: AntiforgeryTokentoken. 

AntiforgeryToken works well with HTML forms. It’s a 2-step process where you place the token inside you HTML page and decorate your handler with ValidateAntiForgeryToken. However, to make it work with AJAX calls it becomes a 3-step process. First, just like the previous method, place your token inside your HTML page. Second, read the token and build your AJAX request data with the following format:

Couple of things here, request must be POST. The name of the token must be __RequestVerificationToken. This is the name of the form field generated by @Html.AntiForgeryToken() helper which is what’s required on the the last step—decorate your method handler ValidateAntiForgeryToken attribute.