How does AntiForgeryToken work?

I am using Security for my .net 3.5 mvc2 web application. My website does not contain user authentication and consists of many ajax calls in .js files.

In my .aspx file I wrote

<%= Html.AntiForgeryToken() %> 

In my .js file function I wrote

 $(document).ready(function() { var token = $('input[name=__RequestVerificationToken]').val(); $.ajax({ url: "/Home/getCurrentLanguage/" + Math.random(), cache: false, type: "POST", async: false, data: {"__RequestVerificationToken":token}, success: function(data) { if (data == "mr") { alert("its Marathi"); } else { alert("its English huh !!!"); } return false; }, error: function(data) { alert("some Error" + data); } }); }); 

In my controller, I wrote

  [AcceptVerbs(HttpVerbs.Post), ValidateAntiForgeryToken] public JsonResult getCurrentLanguage(string id) { return new JsonResult { Data = "mr" }; } 

This works fine for me, but I have 2 questions
Q1. Is this the right approach? If I see the source of the page, I found this code

 <input name="__RequestVerificationToken" type="hidden" value="WFd+q5Mz0K4RHP7zrz+gsloXpr8ju8taxPJmrLO7kbPVYST9zzJZenNHBZqgamPE1KESEj5R0PbNA2c64o83Ao8w8z5JzwCo3zJKOKEQQHg8qSzClLdbkSIkAbfCF5R6BnT8gA==" /> 

but when I created an external html file and copied this __RequestVerificationToken value and passed an ajax call, I get this error
The required anti-counterfeit token was not specified or was invalid. then
Q2. How does the runtime know that this page provides the copied __RequestVerificationToken?

+4
source share
1 answer

This "AntiForgeryToken" is in place to prevent Cross-Site Request Forgery attacks. This system could be compromised by an attacker if your application suffers from Cross-Site Scripting vulnerability.

This token prevents CSRF attacks because, due to policies of the same origin, the attacker can send requests, but he cannot read the token on the page to make the request successful (if it does not have xss vulnerability).

As with Q2, this value must be unique for each user and therefore updated every time the page loads. If this is just a static value, then it is useless to stop the CSRF because the attacker will know this static value.

+2
source

All Articles