How to configure Anti-Forgery Protection in a view-less Web API

倾然丶 夕夏残阳落幕 提交于 2020-06-27 16:29:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!