How to use ValidateAntiForgeryToken at controller level in MVC?

17.9k views Asked by At

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.

2

There are 2 answers

1
Jasen On BEST ANSWER

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://learn.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
1
Jesse Moreland On

You need to include anti forgery token in your view.

@using (Html.BeginForm("Save", "Search", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    // Rest of html
}

That way when you do a post, the anti forgery token is then submitted along with the request.