还需要Html.AntiForgeryToken()吗? [英] Html.AntiForgeryToken() still required?

查看:124
本文介绍了还需要Html.AntiForgeryToken()吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆