ASP.NET Anti-Forgery Tokens With JSON Payloads
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.
cumbersome?
by
Simon S.
"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"? Thats not "simple" anymore.
Why not use
$.ajaxSetup({
headers: { "csrftoken": "myValue" }
});
and check the header instead?
And btw, do we still need to protect against csrf if we use cors?
Re: cumbersome?
by
Roopesh Shenoy
how will the "myValue" come? It has to come from the markup right? ASP.NET helpers allow a anti-forgery token to be generated using the AntiForgeryToken() helper, but it has to be called somewhere in the markup and your JavaScript will have to read that value from there. Correct me if I am wrong.
I'm not very familiar with CORS to comment - I read about the concepts but not sure about the security implications and how robustly it is implemented in all the browsers. Can you shed more light?
Re: cumbersome?
by
Simon S.
I was not really familiar with cors either. I really asked because I didn't know the answer.
But after reading a bit [1] now I know that we need to protect against csrf even with cors.
[1]www.w3.org/TR/cors/#security
Educational Content
Tuning the Size of Your Thread Pool
Kirk Pepperdine May 23, 2013
Co-making Great Products
Jeff Patton May 22, 2013




Hello stranger!
You need to Register an InfoQ account or Login to post comments. But there's so much more behind being registered.Get the most out of the InfoQ experience.
Tell us what you think