将 AD 身份验证添加到 OWIN 服务器中间件管道

Adding AD authentication to OWIN Server Middleware pipeline

我继承了一个使用 OWIN 开发的项目,服务器中间件管理一种 WebApi,以便使用 ApiKeys 与移动设备进行通信。服务器端有一个小的 web 界面(实际上是一组测试页面)但没有添加身份验证。我正在努力思考正在使用的不同框架以及围绕这些 OWIN 技术进行身份验证的方式。

让我先展示一下我有什么:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        log.Info("RT Server app starting up ...");
        // Initialize the ApiKey Needed for ApiClient Library
        ApiClient.ApiKey = Globals.ApiKey;
        // Initialize the Services Library
        Services.Startup.Initialize();//creates a configuration map of values for devices
        // Setup Server Middleware
        app.Use(typeof(ServerMiddleware), "RTrak.Server", "RTrak.Server");
        app.Use(typeof(ServerMiddleware), "RTrak.Server.Pages", "RTrak.Server");
         // HttpListener listener =   (HttpListener)app.Properties["System.Net.HttpListener"];//throws an KeyNotFoundException
         // listener.AuthenticationSchemes = AuthenticationSchemes.IntegratedWindowsAuthentication;
        //ConfigureAuth(app)
    }

    public void ConfigureAuth(IAppBuilder app)
    {
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = MyAuthentication.ApplicationCookie,
            LoginPath = new PathString("/Login"),
            Provider = new CookieAuthenticationProvider(),
            CookieName = "RTrakCookie",
            CookieHttpOnly = true,
            ExpireTimeSpan = TimeSpan.FromHours(12), // ...
        });
    }

ServerMiddleware

   public ServerMiddleware(OwinMiddleware next, string baseNamespace, string defaultClass) : base(next)
    {
        BaseNamespace = baseNamespace;
        DefaultClass = defaultClass;
    }

    public override async Task Invoke(IOwinContext owinContext)
    {
        var absolutePath = owinContext.Request.Uri.AbsolutePath;
        string serverNamespace = BaseNamespace;

        Type type;
        string classToLoad = "";

        if (absolutePath == "/")
            classToLoad = DefaultClass;
        else
        {
            classToLoad = absolutePath.Substring(1).Replace('/', '.');
            if (classToLoad.EndsWith("."))
                classToLoad = classToLoad.Substring(0, classToLoad.Length - 1);
        }
        type = Type.GetType($"{serverNamespace}.{classToLoad}, {serverNamespace}", false, true);

        if (type == null)
        {
            classToLoad += ".Default";
            type = Type.GetType($"{serverNamespace}.{classToLoad}, {serverNamespace}", false, true);
        }

        if (type != null)
        {
            try
            {
                object objService = Activator.CreateInstance(type);
                ((Resource)objService).Execute(owinContext);
            }
            catch (System.MissingMethodException)
            {
                //"403 INVALID URL");
            }
        }
        else
            await Next.Invoke(owinContext);
    }
}

ServerMiddleware 首先调用默认页面 class 即链接到其他测试页面的 HTML 标记

一个想法是添加一个带有 AdAuthenticationService 管理 cookie 模型的 MVC LoginController 来管理配置为 ConfigAuth(app) 行中提到的启动的一部分的登录,但中间件忽略了控制器。 MVC 在这里合适吗?

然后,我正在查看这个 ServerMiddleware 并试图了解如何使用 ActiveDirectory 身份验证拦截默认页面浏览器调用。

我知道我可能忽略了一些东西。非常感谢您提供的任何东西(建议或资源)来帮助我解决这个困惑。

我为解决这个问题所做的是让 OWIN 中间件对象保持独立,除了 Startup.cs 必须定义 CookieAuthentication 路由

        app.UseCookieAuthentication(new Microsoft.Owin.Security.Cookies.CookieAuthenticationOptions
        {
            AuthenticationType = "ApplicationCookie",
            LoginPath = new Microsoft.Owin.PathString("/Auth/Login")
        });

      app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

对于作为 OWIN 资源构建的页面。这些 OWIN 资源 "Pages" 然后检查

                if (!this.Context.Authentication.User.Identity.IsAuthenticated)

然后我实现了一个 MVC 控制器,它使用上面的 AdAuthenticationService 和 UserManager 来管理 AD 凭据和身份,其中 OWIN 资源重定向到 MVC 视图+控制器以进行身份​​验证。该控制器处理登录页面操作。身份验证后,MVC 重定向到 OWIN 资源页面。

因此,只要 OWIN 不尝试定义 MVC 想要使用的路由,OWIN 中间件和 MVC 就可以并存。 Owin 也可以维护自己的身份验证。