问题
I'm implementing a REST API using ASP.NET Core. It is stateless except for the fact that is uses cookies for authentication and therefore is vulnerable to cross-site request forgery (CSRF) attacks.
Luckily, ASP.NET Core provides means as a protection against that: Prevent Cross-Site Request Forgery (XSRF/CSRF) attacks in ASP.NET Core.
As my application does not have any views or pages, I'm only configuring my controllers using services.AddControllers()
in my Startup
.
When hitting a REST endpoint that is attributed with [ValidateAntiForgeryToken]
, I get the following exception:
System.InvalidOperationException: No service for type 'Microsoft.AspNetCore.Mvc.ViewFeatures.Filters.ValidateAntiforgeryTokenAuthorizationFilter' has been registered.
Registering my controllers using services.AddControllersWithViews()
makes this error go away as it internally registers the appropriate service.
According to the docs:
Antiforgery middleware is added to the Dependency injection container when one of the following APIs is called in Startup.ConfigureServices:
AddMvc
MapRazorPages
MapControllerRoute
MapBlazorHub
All of these method seem to me to be view-centric (except MapControllerRoute
which I'm doing in the Configure
method in my Startup
but it doesn't help) and part of the namespace of the missing service is ViewFeatures
. This confuses me because in my understanding, and need to take care of CSRF although I'm developing a pure Web API without views.
Is my understanding wrong? How is CSRF protection configured when no views are involved?
来源:https://stackoverflow.com/questions/62347212/how-to-configure-anti-forgery-protection-in-a-view-less-web-api