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

查看:23
本文介绍了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天全站免登陆