Automatically validate antiforgery tokens for unsafe HTTP methods only

By | April 27, 2018

ASP.NET Core apps don’t generate antiforgery tokens for safe HTTP methods (GET, HEAD, OPTIONS, and TRACE). Instead of broadly applying the ValidateAntiForgeryToken attribute and then overriding it with IgnoreAntiforgeryToken attributes, the AutoValidateAntiforgeryToken attribute can be used. 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

Recommended use of AutoValidateAntiforgeryToken broadly for non-API scenarios. This ensures POST actions are protected by default. The alternative is to ignore antiforgery tokens by default, unless ValidateAntiForgeryToken is applied to individual action methods. It’s more likely in this scenario for a POST action method to be left unprotected by mistake, leaving the app vulnerable to CSRF attacks. All POSTs should send the antiforgery token.

APIs don’t have an automatic mechanism for sending the non-cookie part of the token. The implementation probably depends on the client code implementation. Some examples are shown below:

 

Class-level example:(Controller File)

[Authorize]
[AutoValidateAntiforgeryToken]
public class CustomerController : Controller
{

Global example:(Startup.cs file)

services.AddMvc(options => 
    options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()));

Override global or controller antiforgery attributes

The IgnoreAntiforgeryToken filter is used to eliminate the need for an antiforgery token for a given action (or controller). When applied, this filter overrides ValidateAntiForgeryToken and AutoValidateAntiforgeryToken filters specified at a higher level (globally or on a controller).

[Authorize]
[AutoValidateAntiforgeryToken]
public class CustomerController : Controller
{
    [HttpPost]
    [IgnoreAntiforgeryToken]
    public async Task<IActionResult> SaveCustomer(CustomerViewModel model)
    {
        // no antiforgery token required
    }
}

2 thoughts on “Automatically validate antiforgery tokens for unsafe HTTP methods only

  1. GuQinPu

    I have really learned new things as a result of your site. One other thing I want to say is newer computer system operating systems have a tendency to allow extra memory to be utilized, but they as well demand more storage simply to operate. If one’s computer cannot handle more memory along with the newest software program requires that memory space increase, it may be the time to buy a new Computer. Thanks

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *