C# ValidateAntiForgeryToken 用途、解释和示例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13621934/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ValidateAntiForgeryToken purpose, explanation and example
提问by Tabriz Atayi
Could you explain ValidateAntiForgeryTokenpurpose and show me example about ValidateAntiForgeryTokenin MVC 4?
你能解释一下ValidateAntiForgeryToken 的目的并ValidateAntiForgeryToken在 MVC 4 中向我展示示例吗?
I could not find any examples which explain this attribute?
我找不到任何解释此属性的示例?
采纳答案by Richard Szalay
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.
MVC 的防伪支持将唯一值写入 HTTP-only cookie,然后将相同的值写入表单。提交页面时,如果 cookie 值与表单值不匹配,则会引发错误。
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 ValidateAntiForgeryTokenattribute and place a call to @Html.AntiForgeryToken()in the forms posting to the method.
要使用它,请使用ValidateAntiForgeryToken属性装饰操作方法或控制器,并@Html.AntiForgeryToken()在发布到该方法的表单中调用。
回答by Chandra Malla
The basic purpose of ValidateAntiForgeryToken attribute is to prevent cross-site request forgery attacks.
ValidateAntiForgeryToken 属性的基本目的是防止跨站请求伪造攻击。
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.
跨站点请求伪造是一种从受信任用户的浏览器发送有害脚本元素、恶意命令或代码的攻击。有关这方面的更多信息,请访问 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:
它使用简单,您需要使用 ValidateAntiForgeryToken 属性装饰方法,如下所示:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateProduct(Product product)
{
if (ModelState.IsValid)
{
//your logic
}
return View(ModelName);
}
It is derived from System.Web.Mvc namespace.
它派生自 System.Web.Mvc 命名空间。
And in your view, add this code to add the token so it is used to validate the form upon submission.
在您看来,添加此代码以添加令牌,以便在提交时使用它来验证表单。
@Html.AntiForgeryToken()
回答by Vinayak Savale
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.
Microsoft 为我们提供了我们在应用程序中出于安全目的使用的内置功能,因此没有人可以入侵我们的网站或入侵某些关键信息。
From Purpose Of ValidateAntiForgeryToken In MVC Applicationby Harpreet Singh:
来自Harpreet Singh MVC 应用程序中 ValidateAntiForgeryToken 的目的:
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.
ValidateAntiForgeryToken 的使用
让我们尝试用一个简单的例子来理解这个概念。我不想让它太复杂,这就是为什么我要使用 MVC 应用程序的模板,它已经在 Visual Studio 中可用。我们将一步一步地做到这一点。开始吧。
步骤 1 - 使用默认 Internet 模板创建两个 MVC 应用程序,并将这些名称分别命名为 CrossSite_RequestForgery 和 Attack_Application。
现在,打开 CrossSite_RequestForgery 应用程序的 Web Config 并使用下面给出的连接字符串更改连接字符串,然后保存。
`
<connectionStrings> <add name="DefaultConnection" connectionString="Data Source=local\SQLEXPRESS;Initial Catalog=CSRF; Integrated Security=true;" providerName="System.Data.SqlClient" /> </connectionStrings>
现在,单击工具>> NuGet 包管理器,然后单击包管理器控制台
现在,在包管理器控制台中运行下面提到的三个命令来创建数据库。
Enable-Migrations add-migration first update-database
重要说明 - 我使用代码优先方法创建了数据库,因为我想以开发人员的工作方式制作这个示例。您也可以手动创建数据库。这是你的选择。
- 现在,打开帐户控制器。在这里,您将看到一个类型为 post 的 register 方法。在这个方法之上,应该有一个可用的属性作为 [ValidateAntiForgeryToken]。注释此属性。现在,右键单击注册并单击转到查看。在那里,您将再次找到一个 html 帮助程序,如 @Html.AntiForgeryToken() 。也评论这个。运行应用程序并单击注册按钮。该 URL 将打开为:
http://localhost:52269/Account/Register
注释- 我现在知道所有读者心中提出的问题是为什么需要注释这两个助手,因为每个人都知道它们用于验证请求。然后,我只想让大家知道,这只是因为我想展示应用这些助手之前和之后的区别。
现在,打开第二个应用程序 Attack_Application。然后,打开 Account Controller 的 Register 方法。只需使用简单的方法更改 POST 方法,如下所示。
报名表格
- @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.现在,假设您是一名黑客,并且您知道可以在 CrossSite_RequestForgery 应用程序中注册用户的 URL。现在,您创建了一个伪造站点作为 Attacker_Application 并在 post 方法中放置相同的 URL。
8.立即运行此应用程序并填写注册字段并单击注册。您将看到您已在 CrossSite_RequestForgery 应用程序中注册。如果您检查 CrossSite_RequestForgery 应用程序的数据库,那么您将看到您输入的条目。
- 重要 - 现在,打开 CrossSite_RequestForgery 应用程序并注释掉帐户控制器中的令牌并注册视图。尝试使用相同的过程再次注册。然后,将发生如下错误。
“/”应用程序中的服务器错误。________________________________________ 所需的防伪 cookie“__RequestVerificationToken”不存在。
这就是概念所说的。我们在 View 中添加的内容,即 @Html.AntiForgeryToken() 在加载时生成 __RequestVerificationToken 和在 Controller 方法上可用的 [ValidateAntiForgeryToken]。在发布时间匹配此令牌。如果令牌相同,则表示这是一个有效的请求。
回答by tscissors
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.
在 ASP.Net Core 中,反伪造令牌会自动添加到表单中,因此@Html.AntiForgeryToken()如果您使用 razor 表单元素或使用 IHtmlHelper.BeginForm 并且表单的方法不是 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">
它将为您的表单生成类似于以下内容的输入元素:
<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.
[ValidateAntiForgeryToken]属性可用于操作。除非请求包含有效的防伪令牌,否则对应用此过滤器的操作发出的请求将被阻止。
[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
[AutoValidateAntiforgeryToken]属性可用于控制器。此属性与 ValidateAntiForgeryToken 属性的工作方式相同,不同之处在于它不需要使用以下 HTTP 方法发出的请求的令牌:
GET
HEAD
OPTIONS
TRACE
Additional information: https://docs.microsoft.com/pl-pl/aspnet/core/security/anti-request-forgery
附加信息:https: //docs.microsoft.com/pl-pl/aspnet/core/security/anti-request-forgery

