In simple explanation found on Microsoft docs: ValidateAntiForgeryToken represents an attribute that is used to prevent forgery of a request.
In other terms this attribute is used to prevent cross-site forgery attacks.
Cross site forgery is an attack that posts to your site/form to attempt to submit a hiddent content using an authenticated user’s credential.
Let’s have a realistic scenario of this cross site forgery. Supposed you are logged in to your online banking account. Since you are logged in, you have an active session and you are authenticated, you have all the tokens and stuffs to perform a valid transactions to your accounts. A hacker, who knows that you are logged into your online bank website, also knows the transfer funds URL, he only needs a user who is authenticated to the online banking site and on this example that is YOU.
The hacker then sends you an email with a link that is use for transferring funds. You, as a vulnerable user clicks the link and viola, the site that has no ValidateAntiForgeryToken accepts the request and transfer the funds.
To use the ValidateAntiForgeryToken
attribute, just add it to your controller/method and place a call to @Html.AntiForgeryToken()
in the forms that is posting the method.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult FundTransfer(AccountViewModel model)
{
if (ModelState.IsValid)
{
...
}
return View(model);
}
<form method="post" enctype="multipart/form-data" asp-controller="Account" asp-action="FundTransfer">
@Html.AntiForgeryToken()
... form goes here ...
</form>
When you add the @Html.AntiForgeryToken
in View, it generates _RequestVerificationToken on load time. This is what the ValidateAntiForgeryToken
attribute is looking/matching at post time. When the token is the same, this means its safe and valid.