我有一个使用 OWIN
自托管的 WebApi
项目。
我想对某些 Controller 的操作启用 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);
}
然后,在我的 Controller 中,我创建了两个 Action :
[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 上测试。
我在这里错过了什么?
最佳答案
好吧,我在另一个问题中找到了解决这个问题的方法。 您可以在运行时通过设置 AuthenticationSchemeSelector 方法为每个请求选择身份验证模式,而不是指定多个身份验证模式(这不起作用):
public void Configuration(IAppBuilder app)
{
HttpListener listener = (HttpListener)appBuilder.Properties["System.Net.HttpListener"];
listener.AuthenticationSchemeSelectorDelegate = new
AuthenticationSchemeSelector(GetAuthenticationScheme);
}
private AuthenticationSchemes GetAuthenticationScheme(HttpListenerRequest httpRequest)
{
if(/* some logic... */){
return AuthenticationSchemes.Anonymous;
}
else{
return AuthenticationSchemes.IntegratedWindowsAuthentication;
}
}
虽然不理想(您必须手动检查请求 URL 或请求的其他一些参数来决定使用哪种方法)但它有效。
关于c# - OWIN 托管的 web api : using windows authentication and allow anonymous access,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55868244/