回答

1

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

  • 使用[AutoValidateAntiforgeryToken]验证所有“不安全”方法上的令牌。 (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,但你可以看到在github上issue的草稿。

1

的防伪标记是自动生成并由FormTagHelper加入。 您可以通过添加asp-antiforgery="true"属性禁用/启用该自动功能:

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

基于丹尼尔的回答,我的代码更改为

[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 
    } 

}