[英]Mixed authorization (Windows NTLM & anonymous) in selfhosted owin application not working - “Authorization has been denied for this request”
I am trying to develop selfhosted OWIN WebApp. 我正在尝试开发自托管的OWIN WebApp。 Everything OK, until I tried to integrate Windows (NTLM) authentication. 一切正常,直到我尝试集成Windows(NTLM)身份验证。 Windows authentication works fine if only IntegratedWindowsAuthentication is activated. 如果仅激活IntegratedWindowsAuthentication,则Windows身份验证工作正常。 But I need some of the requests to remain anonymous. 但是我需要一些要求以保持匿名。
I already found that I have to enable both authentication methods: 我已经发现必须启用两种身份验证方法:
AuthenticationSchemes.IntegratedWindowsAuthentication | AuthenticationSchemes.Anonymous
But in such case I get "Authorization has been denied for this request". 但是在这种情况下,我会收到“此请求的授权已被拒绝”。 Tested with Chrome as client ( http://localhost:9009/api/test ). 使用Chrome作为客户端进行测试( http:// localhost:9009 / api / test )。
Please help. 请帮忙。
OWIN startup class: OWIN启动类:
public class Startup
{
public void Configuration(IAppBuilder appBuilder)
{
// Enable Windows & Anonymous Authentification
HttpListener listener = (HttpListener)appBuilder.Properties["System.Net.HttpListener"];
listener.AuthenticationSchemes =
AuthenticationSchemes.IntegratedWindowsAuthentication | AuthenticationSchemes.Anonymous;
HttpConfiguration config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}"
);
appBuilder.UseWebApi(config);
}
}
Main program: 主程序:
static void Main()
{
string baseAddress = "http://localhost:9009/";
// Start OWIN host
using (WebApp.Start<Startup>(url: baseAddress))
{
Console.WriteLine("Server ready");
Console.ReadLine();
}
}
Test controller: 测试控制器:
using System.Collections.Generic;
using System.Security.Principal;
using System.Web.Http;
namespace SelfhostNTAuth
{
public class TestController : ApiController
{
[Authorize]
public IEnumerable<string> Get()
{
WindowsPrincipal user = RequestContext.Principal as WindowsPrincipal;
if (user == null)
{
return new string[] { "unauthorized"};
}
else
{
return new string[] { user.Identity.AuthenticationType, user.Identity.Name };
}
}
}
}
What worked for me was to use the AuthenticationSchemeSelector to return the authentication scheme based on some criteria. 对我有用的是使用AuthenticationSchemeSelector根据某些条件返回身份验证方案。
// Specify the authentication delegate.
listener.AuthenticationSchemeSelectorDelegate =
new AuthenticationSchemeSelector (AuthenticationSchemeForClient);
static AuthenticationSchemes AuthenticationSchemeForClient(HttpListenerRequest request)
{
Console.WriteLine("Client authentication protocol selection in progress...");
// Do not authenticate local machine requests.
if (request.RemoteEndPoint.Address.Equals (IPAddress.Loopback))
{
return AuthenticationSchemes.None;
}
else
{
return AuthenticationSchemes.IntegratedWindowsAuthentication;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.