Html.AntiForgeryToken() 仍然需要吗? [英] Html.AntiForgeryToken() still required?
问题描述
在 ASP.NET .NET4.6 vNext 中是否仍需要 @Html.AntiForgeryToken()
?
Is @Html.AntiForgeryToken()
still required in ASP.NET .NET4.6 vNext?
表单装饰已更改为
<form asp-controller="Account"
asp-action="Login"
asp-route-returnurl="@ViewBag.ReturnUrl"
method="post"
class="form-horizontal"
role="form">
从这里
@using (Html.BeginForm("Login",
"Account",
new { ReturnUrl = ViewBag.ReturnUrl },
FormMethod.Post,
new { @class = "", role = "form" }))
并且不再包含这个
@Html.AntiForgeryToken()
控制器操作仍按预期使用 ValidateAntiForgeryToken
属性进行标记,但它究竟来自哪里?自动?
The Controller Actions are still marked with the ValidateAntiForgeryToken
attribute as expected though so where exactly is it coming from? Automagically?
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
推荐答案
表单标签助手会自动添加防伪令牌.(除非您将其用作标准 html 表单元素,否则手动添加 action
属性).查看表单标签助手的源代码,你会在Process
方法的最后看到如下内容.
The form tag helper will automatically add the anti forgery token. (Unless you use it as a standard html form element, manually adding an action
attribute). Check the source code of the form tag helper, you will see the following at the end of the Process
method.
if (Antiforgery ?? antiforgeryDefault)
{
var antiforgeryTag = Generator.GenerateAntiforgery(ViewContext);
if (antiforgeryTag != null)
{
output.PostContent.AppendHtml(antiforgeryTag);
}
}
如果你检查登录页面的html,你会在表单中看到如下隐藏的输入:
If you check the html of the login page, you will see the following hidden input inside the form:
<input name="__RequestVerificationToken" type="hidden" value="CfDJ8BIeHClDdT9...">
您也可以手动启用/禁用它添加 asp-antiforgery
属性:
You can also manually enable/disable it adding the asp-antiforgery
attribute:
<form asp-controller="Account" asp-action="Register" asp-antiforgery="false" method="post" class="form-horizontal" role="form">
这篇关于Html.AntiForgeryToken() 仍然需要吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!