ValidateAntiForgeryToken purpose, explanation and example
Solution 1:
MVC's anti-forgery support writes a unique value to an HTTP-only cookie and then the same value is written to the form. When the page is submitted, an error is raised if the cookie value doesn't match the form value.
It's important to note that the feature prevents cross site request forgeries. That is, a form from another site that posts to your site in an attempt to submit hidden content using an authenticated user's credentials. The attack involves tricking the logged in user into submitting a form, or by simply programmatically triggering a form when the page loads.
The feature doesn't prevent any other type of data forgery or tampering based attacks.
To use it, decorate the action method or controller with the ValidateAntiForgeryToken
attribute and place a call to @Html.AntiForgeryToken()
in the forms posting to the method.
Solution 2:
The basic purpose of ValidateAntiForgeryToken attribute is to prevent cross-site request forgery attacks.
A cross-site request forgery is an attack in which a harmful script element, malicious command, or code is sent from the browser of a trusted user. For more information on this please visit http://www.asp.net/mvc/overview/security/xsrfcsrf-prevention-in-aspnet-mvc-and-web-pages.
It is simple to use, you need to decorate method with ValidateAntiForgeryToken attribute as below:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateProduct(Product product)
{
if (ModelState.IsValid)
{
//your logic
}
return View(ModelName);
}
It is derived from System.Web.Mvc namespace.
And in your view, add this code to add the token so it is used to validate the form upon submission.
@Html.AntiForgeryToken()
Solution 3:
In ASP.Net Core anti forgery token is automatically added to forms, so you don't need to add @Html.AntiForgeryToken()
if you use razor form element or if you use IHtmlHelper.BeginForm and if the form's method isn't GET.
It will generate input element for your form similar to this:
<input name="__RequestVerificationToken" type="hidden"
value="CfDJ8HSQ_cdnkvBPo-jales205VCq9ISkg9BilG0VXAiNm3Fl5Lyu_JGpQDA4_CLNvty28w43AL8zjeR86fNALdsR3queTfAogif9ut-Zd-fwo8SAYuT0wmZ5eZUYClvpLfYm4LLIVy6VllbD54UxJ8W6FA">
And when user submits form this token is verified on server side if validation is enabled.
[ValidateAntiForgeryToken]
attribute can be used against actions. Requests made to actions that have this filter applied are blocked unless the request includes a valid antiforgery token.
[AutoValidateAntiforgeryToken]
attribute can be used against controllers. This attribute works identically to the ValidateAntiForgeryToken attribute, except that it doesn't require tokens for requests made using the following HTTP methods:
GET HEAD OPTIONS TRACE
Additional information: docs.microsoft.com/aspnet/core/security/anti-request-forgery