How to use ValidateAntiForgeryToken at controller level in MVC?

LP13 picture LP13 · Jan 4, 2017 · Viewed 12.5k times · Source

I have ASP.NET Core application. I have been using ValidateAntiForgeryToken attribute on all POST action methods so far.

Now i am thinking to useValidateAntiForgeryToken at controller level so it can take care of both POST and GET methods.

Below is sample controller

[ValidateAntiForgeryToken]
public class SearchController : Controller
{
    public SearchController()
    {
    }

    [HttpGet]
    public IActionResult Index()
    {           
        return View();
    }      

    [HttpPost]
    public IActionResult Save(MyModel model)
    {

    }

}

When user accesses the URL http://localhost/search, im not sure how Index action method will receive forgerytoken? Right now i get error Bad Request because there is no token included in the request.

Answer

Jasen picture Jasen · Jan 4, 2017

From http://blog.stevensanderson.com/2008/09/01/prevent-cross-site-request-forgery-csrf-using-aspnet-mvcs-antiforgerytoken-helper/

Limitations of the Anti-Forgery helpers

It only works with POST requests, not GET requests. Arguably this isn’t a limitation, because under the normal HTTP conventions, you shouldn’t be using GET requests for anything other than read-only operations.

So it isn't useful at the controller level.

ASP.NET Core

[ValidateAntiforgeryToken] on the controller has limitations.

https://docs.microsoft.com/en-us/aspnet/core/security/anti-request-forgery?view=aspnetcore-2.1

ASP.NET Core doesn't support adding antiforgery tokens to GET requests automatically.

Controller-level support is improved with [AutoValidateAntiforgeryToken]

This attribute works identically to the ValidateAntiForgeryToken attribute, except that it doesn't require tokens for requests made using the following HTTP methods:

  • GET
  • HEAD
  • OPTIONS
  • TRACE