ASP.NET MVC has AntiForgeryToken helper that allow you to detect and block CSRF attacks using user-specific tokens. However when making primarily ajax requests or using javascript frameworks such as Knockout and Backbone which have JSON payloads, the approach needs to change a bit.
AntiForgeryToken helper works with Form posts by having a hidden field in the form with the token. ValidateAntiForgeryToken only looks at the Form values submitted. For making this work with a JSON request, you can use one of the following approaches -
- For simple JQuery ajax posts, you can just create a separate form on every page with a field having the token and use it explicitly in your post requests
- Sergey Barskiy shows how to create your own attribute to parse JSON payloads differently from normal payloads
- Justin Etheredge shows how to use your own helper method to add meta-head tag and a custom attribute
All the above solutions rely on the setting the value of __RequestVerificationToken field directly. This field name is a constant used in the MVC framework.
To learn more about how ASP.NET MVC token helpers prevent CSRF attacks, you can read Steven Sandersons’ article introducing this.