Anti-forgery tokens using AJAX

It is very common to use AJAX to post data to or get data from the server. An AJAX request sends the JSON data to server. It doesn't send the HTML form data. To achieve sending the token via an AJAX post, we need to use the custom HTTP header. Using Razor syntax, we can generate the tokens by calling the AntiForgery.GetTokens() method and attach it to the request as given in the following code:

<script> @functions{ public string GetAntiForgeryTokenValue () { string tokenInCookie, tokenInForm; AntiForgery.GetTokens(null, out tokenInCookie, out tokenInForm); return tokenInCookie + ":" + tokenInForm; } } $.ajax("/api/contacts", { type: "get", headers: { 'AntiForgeryToken': '@GetAntiForgeryTokenValue()' }, success: function ...

Get ASP.NET Web API Security Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.