Could you explain ValidateAntiForgeryToken purpose and show me example about ValidateAntiForgeryToken
in MVC 4?
I could not find any examples which explain this attribute?
This question is related to
c#
asp.net-mvc
asp.net-mvc-4
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
Microsoft provides us built-in functionality which we use in our application for security purposes, so no one can hack our site or invade some critical information.
From Purpose Of ValidateAntiForgeryToken In MVC Application by Harpreet Singh:
Use of ValidateAntiForgeryToken
Let’s try with a simple example to understand this concept. I do not want to make it too complicated, that’s why I am going to use a template of an MVC application, already available in Visual Studio. We will do this step by step. Let’s start.
Step 1 - Create two MVC applications with default internet template and give those names as CrossSite_RequestForgery and Attack_Application respectively.
Now, open CrossSite_RequestForgery application's Web Config and change the connection string with the one given below and then save.
`
<connectionStrings> <add name="DefaultConnection" connectionString="Data Source=local\SQLEXPRESS;Initial Catalog=CSRF; Integrated Security=true;" providerName="System.Data.SqlClient" /> </connectionStrings>
Now, click on Tools >> NuGet Package Manager, then Package Manager Console
Now, run the below mentioned three commands in Package Manager Console to create the database.
Enable-Migrations add-migration first update-database
Important Notes - I have created database with code first approach because I want to make this example in the way developers work. You can create database manually also. It's your choice.
- Now, open Account Controller. Here, you will see a register method whose type is post. Above this method, there should be an attribute available as [ValidateAntiForgeryToken]. Comment this attribute. Now, right click on register and click go to View. There again, you will find an html helper as @Html.AntiForgeryToken() . Comment this one also. Run the application and click on register button. The URL will be open as:
http://localhost:52269/Account/Register
Notes- I know now the question being raised in all readers’ minds is why these two helpers need to be commented, as everyone knows these are used to validate request. Then, I just want to let you all know that this is just because I want to show the difference after and before applying these helpers.
Now, open the second application which is Attack_Application. Then, open Register method of Account Controller. Just change the POST method with the simple one, shown below.
Registration Form
- @Html.LabelFor(m => m.UserName) @Html.TextBoxFor(m => m.UserName)
- @Html.LabelFor(m => m.Password) @Html.PasswordFor(m => m.Password)
- @Html.LabelFor(m => m.ConfirmPassword) @Html.PasswordFor(m => m.ConfirmPassword)
7.Now, suppose you are a hacker and you know the URL from where you can register user in CrossSite_RequestForgery application. Now, you created a Forgery site as Attacker_Application and just put the same URL in post method.
8.Run this application now and fill the register fields and click on register. You will see you are registered in CrossSite_RequestForgery application. If you check the database of CrossSite_RequestForgery application then you will see and entry you have entered.
- Important - Now, open CrossSite_RequestForgery application and comment out the token in Account Controller and register the View. Try to register again with the same process. Then, an error will occur as below.
Server Error in '/' Application. ________________________________________ The required anti-forgery cookie "__RequestVerificationToken" is not present.
This is what the concept says. What we add in View i.e. @Html.AntiForgeryToken() generates __RequestVerificationToken on load time and [ValidateAntiForgeryToken] available on Controller method. Match this token on post time. If token is the same, then it means this is a valid request.
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()
Source: Stackoverflow.com