Reputation: 2009
I have an endpoint with those attributes:
[HttpPost]
[ValidateAntiForgeryToken]
[Route("[controller]/[action]")]
When I applied IgnoreAntiforgeryTokenAttribute
globally
.AddMvc(opts =>
{
opts.Filters.Add(typeof(CustomExceptionFilter));
opts.Filters.Add(new IgnoreAntiforgeryTokenAttribute());
// or
opts.Filters.Add(typeof(IgnoreAntiforgeryTokenAttribute));
})
It didn't disable that [ValidateAntiForgeryToken]
, but when I did something like that:
[HttpPost]
[ValidateAntiForgeryToken]
[IgnoreAntiforgeryToken]
[Route("[controller]/[action]")]
then it was disabled, why?
Upvotes: 2
Views: 1550
Reputation: 29996
For built-in ValidateAntiForgeryToken
, you could not disable it by IgnoreAntiforgeryTokenAttribute
in the Startup.cs
. You could refre Default order of execution.
For a workaround, you could implement your own ValidateAntiforgeryTokenAuthorizationFilter
like
public class CustomValidateAntiforgeryTokenAuthorizationFilter : ValidateAntiforgeryTokenAuthorizationFilter
{
public CustomValidateAntiforgeryTokenAuthorizationFilter(IAntiforgery antiforgery, ILoggerFactory loggerFactory)
:base(antiforgery, loggerFactory)
{
}
protected override bool ShouldValidate(AuthorizationFilterContext context)
{
var filters = context.Filters;
if (filters.Where(f => f.GetType() == typeof(IgnoreAntiforgeryTokenAttribute)) != null)
{
return false;
}
else
{
return base.ShouldValidate(context);
}
}
}
And register by ValidateAntiforgeryTokenAuthorizationFilter
like
services.AddMvc(options => {
options.Filters.Insert(0, new IgnoreAntiforgeryTokenAttribute());
options.Filters.Add(typeof(WebApiExceptionFilter)); // by type
});
services.AddScoped<ValidateAntiforgeryTokenAuthorizationFilter, CustomValidateAntiforgeryTokenAuthorizationFilter > ();
Upvotes: 2
Reputation: 46571
Try inserting the filter at the top of the list so it takes precedence of existing filters, such as the AutoValidateAntiforgeryTokenAttribute
:
opts.Filters.Insert(0, new IgnoreAntiforgeryTokenAttribute());
Upvotes: 1