C# 自托管owin应用程序中的混合授权(Windows NTLM“匿名”)不起作用;此请求的授权已被拒绝”;
我正在尝试在WebApp中开发自托管的OW。一切正常,直到我尝试集成Windows(NTLM)身份验证。如果仅激活IntegratedWindowsAuthentication,Windows身份验证工作正常。但我需要一些匿名的请求 我已经发现我必须启用两种身份验证方法:C# 自托管owin应用程序中的混合授权(Windows NTLM“匿名”)不起作用;此请求的授权已被拒绝”;,c#,asp.net-web-api,owin,ntlm-authentication,self-host-webapi,C#,Asp.net Web Api,Owin,Ntlm Authentication,Self Host Webapi,我正在尝试在WebApp中开发自托管的OW。一切正常,直到我尝试集成Windows(NTLM)身份验证。如果仅激活IntegratedWindowsAuthentication,Windows身份验证工作正常。但我需要一些匿名的请求 我已经发现我必须启用两种身份验证方法: AuthenticationSchemes.IntegratedWindowsAuthentication | AuthenticationSchemes.Anonymous 但在这种情况下,我得到“此请求的授权已被拒绝”。
AuthenticationSchemes.IntegratedWindowsAuthentication | AuthenticationSchemes.Anonymous
但在这种情况下,我得到“此请求的授权已被拒绝”。使用Chrome作为客户端()进行测试
请帮忙
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);
}
}
主程序:
static void Main()
{
string baseAddress = "http://localhost:9009/";
// Start OWIN host
using (WebApp.Start<Startup>(url: baseAddress))
{
Console.WriteLine("Server ready");
Console.ReadLine();
}
}
static void Main()
{
字符串基地址=”http://localhost:9009/";
//在主机中启动OWIN
使用(WebApp.Start(url:baseAddress))
{
Console.WriteLine(“服务器就绪”);
Console.ReadLine();
}
}
测试控制器:
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 };
}
}
}
}
使用System.Collections.Generic;
使用System.Security.Principal;
使用System.Web.Http;
名称空间SelfhostNTAuth
{
公共类TestController:ApicController
{
[授权]
公共IEnumerable Get()
{
WindowsPrincipal用户=RequestContext.Principal作为WindowsPrincipal;
if(user==null)
{
返回新字符串[]{“unauthorized”};
}
其他的
{
返回新字符串[]{user.Identity.AuthenticationType,user.Identity.Name};
}
}
}
}
对我有效的方法是使用返回基于某些标准的身份验证方案
// 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;
}
}