Asp.net-Core-Mvc

Html.AntiForgeryToken() 仍然需要嗎?

  • June 20, 2015

@Html.AntiForgeryToken()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按預期標記了屬性,那麼它到底來自哪裡?自動?

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)

表單標籤助手將自動添加防偽令牌。(除非您將其用作標準 html 表單元素,否則手動添加action屬性)。查看表單標籤助手的原始碼,您將在方法末尾看到以下內容Process

if (Antiforgery ?? antiforgeryDefault)
{
   var antiforgeryTag = Generator.GenerateAntiforgery(ViewContext);
   if (antiforgeryTag != null)
   {
       output.PostContent.AppendHtml(antiforgeryTag);
   }
}

如果您檢查登錄頁面的 html,您將在表單中看到以下隱藏輸入:

<input name="__RequestVerificationToken" type="hidden" value="CfDJ8BIeHClDdT9...">

您還可以手動啟用/禁用它添加asp-antiforgery屬性:

<form asp-controller="Account" asp-action="Register" asp-antiforgery="false" method="post" class="form-horizontal" role="form">

引用自:https://stackoverflow.com/questions/30959972