【问题标题】:Command equivalent to AntiForgery.Validate() in asp.net-core命令等效于 asp.net-core 中的 AntiForgery.Validate()
【发布时间】:2017-03-25 03:17:34
【问题描述】:
在 asp.net-core 中是否存在类似于 AntiForgery.Validate(); 的命令来验证操作正文中的防伪令牌?
dotnet 4.5.1 中的代码示例:
public ActionResult Index()
{
if (!User.Identity.IsAuthenticated)
{
System.Web.Helpers.AntiForgery.Validate();
}
// rest of action
}
【问题讨论】:
标签:
c#
asp.net-core
asp.net-core-mvc
.net-core
antiforgerytoken
【解决方案1】:
防伪令牌由FormTagHelper 自动生成和添加。
您可以通过添加asp-antiforgery="true" 属性来禁用/启用此自动功能:
<form asp-controller="Account" asp-action="LogOff" asp-antiforgery="true"
method="post" id="logoutForm" class="navbar-right">
</form>
【解决方案2】:
可以使用控制器中的过滤器属性自动完成防伪令牌验证。
- 使用
[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 中看到它的草稿。
【解决方案3】:
根据丹尼尔的回答,我将代码更改为
[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 作为服务注入。
项目.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
}
}