Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
939 views
in Technique[技术] by (71.8m points)

asp.net core mvc - Html.AntiForgeryToken() still required?

Is @Html.AntiForgeryToken() still required in ASP.NET .NET4.6 vNext?

The form decorations have changed to

<form asp-controller="Account" 
      asp-action="Login" 
      asp-route-returnurl="@ViewBag.ReturnUrl" 
      method="post" 
      class="form-horizontal" 
      role="form">

From this

@using (Html.BeginForm("Login", 
                       "Account", 
                       new { ReturnUrl = ViewBag.ReturnUrl }, 
                       FormMethod.Post, 
                       new { @class = "", role = "form" }))

And no longer include this

@Html.AntiForgeryToken()

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
    }
}

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...">

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">

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...