Command equivalent to AntiForgery.Validate() in as

2019-07-19 08:24发布

问题:

Exists, in asp.net-core, a command similar to AntiForgery.Validate(); to validate antiforgery token in the action body?

Code example in dotnet 4.5.1:

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

    // rest of action
}

回答1:

Antiforgery token validation can be done automatically using filter attributes in your controllers.

  • Use [AutoValidateAntiforgeryToken] to validate the token on all "unsafe" methods. (Methods other than GET, HEAD, TRACE, OPTIONS).
  • Use [ValidateAntiforgeryToken] to always validate the token
  • Use [IgnoreAntiforgeryToken] to ignore token validation

You can combine these attributes to achieve the granularity you need. For example:

//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(){ }
}

I have noticed the documentation isnt fully ready in the docs site, but you can see a draft of it in the github issue.



回答2:

Based on Daniel`s answer, I change the code to

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

Another option, based on docs draft, is inject Antiforgery as an service.

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();
    ...

Then validate on controller.

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
    }

}


回答3:

The antiforgery token is automagically generated and added by FormTagHelper. You can disable/enable this automatic feature by adding the asp-antiforgery="true" attribute:

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