0

我正在尝试开发自托管的 OWIN WebApp。一切正常,直到我尝试集成 Windows (NTLM) 身份验证。如果仅激活了 IntegratedWindowsAuthentication,则 Windows 身份验证工作正常。但我需要一些要求保持匿名。

我已经发现我必须启用两种身份验证方法:

AuthenticationSchemes.IntegratedWindowsAuthentication | AuthenticationSchemes.Anonymous

但在这种情况下,我得到“此请求的授权已被拒绝”。使用 Chrome 作为客户端 ( http://localhost:9009/api/test ) 进行了测试。

请帮忙。

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();
        }
    }

测试控制器:

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 };
        }
    }
}
}
4

1 回答 1

1

对我有用的是使用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;
    }
}
于 2019-05-17T17:38:52.727 回答