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?
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.
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.
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.
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.
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>();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With