Using ASP.NET Core 3.1 I am creating a new API for a single page application that is built separately and served as static files.
I thought that I would be served well with .AddControllers() as I'm just doing an API, no views.
Naturally I wanted to add CSRF protection. I started with .AddAntiforgery() and in the controllers options:
options.Filters.Add<AutoValidateAntiforgeryTokenAttribute>();
But that failed, because the attributes requires a service AutoValidateAntiforgeryTokenAuthorizationFilter, which wasn't registered and is an internal type.
This is where things started going bad.
First, I would suggest improving the docs and error messages: the antiforgery docs should clearly say what are the precise requirements for making it work. Ideally when an internal service is not found, the error message should point out what configuration is missing. Even if it's just a generic link to a page where all internal services are listed with their matching configuration call(s).
Googling did not bring up anything useful so I started looking at the source code on Github.
It seems that this internal type is only added to services if you use AddMvcCore and then AddViews (I found two other methods but they're even less appropriate).
Unless I missed something (please let me know), it feels wrong that to use a controller attribute you have to opt into the full views/templating stuff.
Antiforgery is a security practice that every web api should include, it should be usable with .AddControllers or even .AddMvcCore without views.