Search code examples
c#asp.net-coreasp.net-core-mvc.net-coreantiforgerytoken

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


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
}

Solution

  • 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.