heath
heath

Reputation: 1109

Global Anti-Forgery Token validation issues

I followed the code in this link in my Core 2.2 web app Global Antiforgery Token Validation in ASP.NET Core

It works great. However, I now need to be able to exclude certain actions from running in this middleware. I was thinking I could create an attribute to put on the methods I'd like to exclude and only run the validation if it's a POST request (as it does now) AND my new attribute is not on the action. However, I can't figure out how I could check for the existence of an attribute within this middleware. And maybe that's not even the best way to do it so I'm open to other suggestions.

Upvotes: 1

Views: 880

Answers (1)

Nan Yu
Nan Yu

Reputation: 27588

You can simply disable the validation of anti-forgery tokens for an action by applying the [IgnoreAntiforgeryToken] attribute :

[IgnoreAntiforgeryToken]
public IActionResult Create(customModel model)

For your idea , it is too early to know whether custom attribute is applying to current route in middleware .

Update :

You don't need to use middleware , you can add the recommended global filter AutoValidateAntiforgeryToken to protect POST method by default :

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

})

And in specific action add to IgnoreAntiforgeryToken override global or controller antiforgery attributes . See document .

Upvotes: 3

Related Questions