Html.AntiForgeryToken() still required?
Asked Answered
D

1

34

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)
Druse answered 20/6, 2015 at 23:49 Comment(0)
M
57

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">
Multiplication answered 21/6, 2015 at 11:50 Comment(3)
As of MVC 6, Asp.net 5 RC1 the Tag Helper is "asp-antiforgery" not "asp-anti-forgery" not sure if it was already like that or changed. <br/> <form asp-controller="Account" asp-action="Register" asp-antiforgery="false" method="post" class="form-horizontal" role="form">Basanite
it also seems that the <form> needs a separate closing tag </form> for this attribute to generate. it does not seem to work with a self-closing form tag <form/>. maybe because self-closing form tags are not valid HTML5, in which case the lack of a compiler or even a runtime error is still annoyingGeorgiageorgian
You say (Unless you use it as a standard html form element, manually adding an action attribute) But what if the form points to itself with no action attribute at all?Prizewinner

© 2022 - 2024 — McMap. All rights reserved.