首页 > 解决方案 > HostAuthenticationFilter 有什么作用?

问题描述

谁能解释一下我的 WebApiConfig.cs 文件的 Register() 方法中这两行代码的含义。

// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

我假设它在整个应用程序范围内添加 HostAuthentication。但即使我的请求没有传递不记名令牌,我仍然能够获取数据。那么添加这个过滤器有什么意义呢?

标签: c#asp.net-web-apiowin

解决方案


我通常在我的代码中保留以下注释,以提醒它们的用途。

// Configure Web API to use only bearer token authentication.
// If you don't want the OWIN authentication to flow to your Web API then call 
// SuppressDefaultHostAuthentication on your HttpConfiguration. 
// This blocks all host level authentication at that point in the pipeline.
config.SuppressDefaultHostAuthentication();
//config.Filters.Add(new HostAuthenticationFilter(Microsoft.Owin.Security.OAuth.OAuthDefaults.AuthenticationType));

// “Host-level authentication” is authentication performed by the host (such as IIS), 
// before the request reaches the Web API framework. 
// ----
// Often, you may want to to enable host-level authentication for the rest of your application, 
// but disable it for your Web API controllers. For example, a typical scenario is to 
// enable Forms Authentication at the host level, but use token-based authentication for Web API.
// ----
// To disable host-level authentication inside the Web API pipeline, call config.SuppressHostPrincipal() 
// in your configuration. This causes Web API to remove the IPrincipal from any request that enters 
// the Web API pipeline. Effectively, it "un-authenticates" the request.
config.SuppressHostPrincipal();

此外,如果您仍然可以访问操作数据,则很可能您没有将[Authorize]属性应用于控制器或操作以限制访问。

相关阅读Host authentication and Web API with OWIN and active vs. passive authentication middleware


推荐阅读