Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does adding AutoValidateAntiForgeryTokenAttribute by type not work?

In ASP.NET Core you can validate all non-GET requests by including this line in Startup.cs (docs):

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

However, if you add the filter by type (using typeof or the generic Add<T> method), the validation doesn't seem to work:

// Doesn't work
services.AddMvc(options => options.Filters.Add(typeof(AutoValidateAntiforgeryTokenAttribute));
// Doesn't work either
services.AddMvc(options => options.Filters.Add<AutoValidateAntiforgeryTokenAttribute>());

See https://github.com/davidgruar/GlobalFilterDemo for a minimal repro.

What is going on here?

like image 766
Blisco Avatar asked Apr 11 '18 12:04

Blisco


People also ask

How is Antiforgery token validated?

Require antiforgery validation The ValidateAntiForgeryToken attribute requires a token for requests to the action methods it marks, including HTTP GET requests. If the ValidateAntiForgeryToken attribute is applied across the app's controllers, it can be overridden with the IgnoreAntiforgeryToken attribute.

What is Autovalidateantiforgerytoken?

An attribute that causes validation of antiforgery tokens for all unsafe HTTP methods. An antiforgery token is required for HTTP methods other than GET, HEAD, OPTIONS, and TRACE. It can be applied at as a global filter to trigger validation of antiforgery tokens by default for an application.

How do I make an anti forgery token?

If you want to merely generate an anti-forgery token somewhere on the page, you can either generate a new form with the method set to POST... ..and then use jQuery or similar to select the value generated by these methods, and include it in your AJAX request.

What is Antiforgerytoken in asp net core?

The Action method is decorated with the following attributes. HttpPost: The HttpPost attribute which signifies that the method will accept Http Post requests. ValidateAntiForgeryToken: The ValidateAntiForgeryToken attribute is used to prevent cross-site request forgery attacks.


1 Answers

You need to register the type with the DI container. I just tried and it works.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc(options =>
    {
        // This works
        //options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());

        // These variants don't work
        //options.Filters.Add<AutoValidateAntiforgeryTokenAttribute>();
        options.Filters.Add(typeof(AutoValidateAntiforgeryTokenAttribute));
    });

    services.AddScoped<AutoValidateAntiforgeryTokenAttribute>();
}
like image 152
Thangadurai Avatar answered Sep 27 '22 19:09

Thangadurai