命令相当于 asp.net-core 中的 AntiForgery.Validate()

Command equivalent to AntiForgery.Validate() in asp.net-core

在asp.net-core中是否存在类似于AntiForgery.Validate();的命令来验证动作主体中的防伪令牌?

dotnet 4.5.1 中的代码示例:

public ActionResult Index()
{
    if (!User.Identity.IsAuthenticated)
    {
        System.Web.Helpers.AntiForgery.Validate();
    }

    // rest of action
}

防伪令牌由 FormTagHelper 自动生成并添加。 您可以通过添加 asp-antiforgery="true" 属性 disable/enable 此自动功能:

<form asp-controller="Account" asp-action="LogOff" asp-antiforgery="true" 
      method="post" id="logoutForm" class="navbar-right">
</form>

可以使用控制器中的过滤器属性自动完成防伪令牌验证。

  • 使用 [AutoValidateAntiforgeryToken] 在所有 "unsafe" 方法上验证令牌。 (GET、HEAD、TRACE、OPTIONS 以外的方法)。
  • 使用[ValidateAntiforgeryToken]始终验证令牌
  • 使用[IgnoreAntiforgeryToken]忽略令牌验证

您可以组合这些属性来实现您需要的粒度。例如:

//Validate all 'unsafe' actions except the ones with the ignore attribute
[AutoValidateAntiforgeryToken]
public class MyApi: Controller
{
    [HttpPost]
    public IActionResult DoSomething(){ }
    [HttpPut]
    public IActionResult DoSomethingElse(){ }

    [IgnoreAntiforgeryToken]   
    public IActionResult DoSomethingSafe(){ }
}

//Validate only explicit actions
public class ArticlesController: Controller
{
    public IActionResult Index(){ }

    [ValidateAntiforgeryToken]
    [HttpPost]   
    public IActionResult Create(){ }
}

我注意到 docs site, but you can see a draft of it in the github issue 中的文档尚未完全准备好。

根据大牛的回答,我把代码改成了

[HttpPost]
[AllowAnonymous]
[IgnoreAntiforgeryToken]
public ActionResult Index()
{
    if (!User.Identity.IsAuthenticated)
    {
        return NewIndex();
    }

    // rest of action
}

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult NewIndex()
{
    // body of new action
}

基于 docs draft 的另一个选项是将 Antiforgery 作为服务注入。

Project.json

"Microsoft.AspNetCore.Antiforgery": "1.0.0" 

Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IAntiforgery antiforgery)
{
    ...


public void ConfigureServices(IServiceCollection services)
{
    services.AddAntiforgery();
    ...

然后在控制器上验证。

public class MyController : Controller
{
    private readonly IAntiforgery _antiforgery;

    public AccountController(IAntiforgery antiforgery)
    {
        _antiforgery = antiforgery; 
    }

    public ActionResult Index()
    {
        if (!User.Identity.IsAuthenticated)
        {
            await _antiforgery.ValidateRequestAsync(HttpContext);
        }

        // rest of action
    }

}