【发布时间】:2019-09-16 00:07:32
【问题描述】:
我有一个使用 OWIN 自托管的 WebApi 项目。
我想对控制器的某些操作启用 Windows 身份验证,但允许匿名调用其他操作。
因此,根据我在网上找到的一些示例,我在 Statrup 类中设置了这样的 WebApi:
public void Configuration(IAppBuilder appBuilder)
{
HttpListener listener = (HttpListener)appBuilder.Properties["System.Net.HttpListener"];
listener.AuthenticationSchemes = AuthenticationSchemes.IntegratedWindowsAuthentication | AuthenticationSchemes.Anonymous; //Allow both WinAuth and anonymous auth
//setup routes and other stuff
//...
//Confirm configuration
appBuilder.UseWebApi(config);
}
然后,在我的控制器中,我创建了两个动作:
[HttpGet]
[Authorize]
public HttpResponseMessage ProtectedAction()
{
//do stuff...
}
[HttpGet]
[AllowAnonymous]
public HttpResponseMessage PublicAction()
{
//do stuff...
}
但是,这不起作用。
调用标记为 AllowAnonymous 的操作按预期工作,但调用标记为 Authorize 的操作总是返回 401 错误和以下消息:
{
"Message": "Authorization has been denied for this request."
}
即使调用方支持 Windows 身份验证,也已在浏览器(Chrome 和 Edge)和 Postman 上进行了测试。
我在这里错过了什么?
【问题讨论】:
-
你是如何调用 API 的?可能您的 API 客户端您没有通过 useDefaultCredentials = true。
-
@ManojChoudhari:正如我在问题中所说,我尝试使用 Postman(配置了 NTLM 身份验证)和与服务器在同一台机器上运行的浏览器(Chrome 和 Edge),因此它们应该自动进行身份验证默认。两者都失败了。请注意,如果我在 HttpListener 中仅启用
IntegratedWindowsAuthentication,然后不使用 Authorize/AllowAnonymous 属性,则身份验证按预期工作(使用 Postman 和浏览器)。但是,如果我这样做,我将无法将某些操作标记为已授权,而将某些操作标记为匿名,这正是我想要做的。 -
你是否在configure方法中使用了`appBuilder.Use(typeof(WinAuthMiddleware));`?
-
@ManojChoudhari:什么是 WinAuthMiddleware 类,我在哪里可以找到它?它是 nuget 包的一部分吗?
-
还有一件事 - 您是否在 IIS / IIS Express 中托管此 Web API?您是否检查了 IIS 设置中是否同时启用了 Windows/匿名身份验证。
标签: c# asp.net-web-api owin