0

i was reading about AntiForgeryToken but do not understand the actual use or importance. i saw people wrote a code like in their form as

@using (Html.BeginForm("Create", "Register")) 
{ 
    @Html.AntiForgeryToken()  
}

so what it does....it will generate a unique token and when form will post then this unique toke will pass and as well as a cookie will pass with same unique token value and two unique data will compare at server end that both are equal or not. if not then some tamper occur.

i just do not understand if other form field value change or tamper then how that tampering can be determine. suppose we often store valuable data inside hidden fields. if i need to secure that hidden fields value then how AntiForgeryToken can help us?

can we use AntiForgeryToken to wrap up those valuable data inside it and later compare at server end.

can anyone give me bit of sample code by which i can put 3 valuable data in my page and if tamper then a friendly message will be show to user. guide me how to do it. thanks

Thomas
  • 33,544
  • 126
  • 357
  • 626

1 Answers1

6

The idea behind the AntiForgeryToken is to prevent data being posted from a "fake" source. An attacker using a fake (forged) form can trick the user to submit any kind of data using their current session context. As you can imagine this can do quite a lot of damage.

A way to prevent this is to have a hidden field on your forms containing user specific data(something random) that is stored in the session, so that the bad guys can't forge it. In this case when a user posts the data, but doesn't have the user specific token, you can treat is as being malicious.

I think you have a misconception that the anti forgery token is about detecting whether the data posted has been "tempered" with, which it is not.

Here is more on this.

Dimitar Dimitrov
  • 14,868
  • 8
  • 51
  • 79
  • i want to show a custom message or redirect user to a page when action method will call and AntiForgeryToken validation check will faul means something got forge by attacker. so just guide me how to catch when AntiForgeryToken validation will fail at action method end. thanks – Thomas Sep 24 '13 at 10:42
  • @Thomas The easiest would be to add a `[ValidateAntiForgeryToken]` attribute to your action method. This will throw an exception if the token was forged. In case you want to detect when this happens you can catch the exception in your `Global.asax` and do whatever you need to there. – Dimitar Dimitrov Sep 24 '13 at 11:05