12

First of all I'm still a starter in MVC4, after noticing many actions are decorated with [ValidateAntiForgeryToken], I googled that, but still kind of confused.

Can anybody explain that concept using a simplest example?

LifeScript
  • 1,116
  • 5
  • 15
  • 24

2 Answers2

18

In simple words it prevents external post requests. So, nobody can use your methods from other sites.

How it works. You are having AntiForgeryToken in your Html.BeginForm in View.

@using (Html.BeginForm()){

@Html.AntiForgeryToken()

//** fields of form

}

When you submit form, you sends data to your Controller method. If method has ValidateAntiForgeryToken attribute, it validates if data you are sending has your ForgeryToken.

[ValidateAntiForgeryToken]
public ViewResult Update()
{
}

ForgeryToken is generated once per session.

Andrey Gubal
  • 3,481
  • 2
  • 18
  • 21
6

Lots of info on the AntiForgeryToken here: http://blog.codeville.net/2008/09/01/prevent-cross-site-request-forgery-csrf-using-aspnet-mvcs-antiforgerytoken-helper/

This is to prevent a Cross-Site Request Forgery (CSRF). It's pretty standard behavior to click 'Save' sumbit a form and perform some action on the server, i.e. save a user's details. How do you know the user submitting the form is the user they claim to be? In most cases you'd use some cookie or windows based auth.

What if an attacker lures you to a site which submits exactly the same form in a little hidden IFRAME? Your cookies get submitted intact and the server doesn't see the request as any different to a legit request. (As gmail has discovered: http://www.gnucitizen.org/blog/google-gmail-e-mail-hijack-technique/)

The anti-forgery token prevents this form of attack by creating a additional cookie token everytime a page is generated. The token is both in the form and the cookie, if the form and cookie don't match we have a CSRF attack (as the attacker wouldn't be able to read the anti-forgery token using the attack described above).

And what does the salt do, from the article above:

Salt is just an arbitrary string. A different salt value means a different anti-forgery token will be generated. This means that even if an attacker manages to get hold of a valid token somehow, they can’t reuse it in other parts of the application where a different salt value is required.

How is the token generated? Download the source, and have a look at the AntiForgeryDataSerializer, AntiForgeryData classes.This has a duplicate.

Community
  • 1
  • 1
Bhushan Firake
  • 9,338
  • 5
  • 44
  • 79