客户端证书映射自托管Owin端点中的身份验证

FXb*_*ers 7 c# ssl active-directory owin katana

是否有可能(如果是,如何?)配置自托管owin端点以使用A/D的客户端证书映射身份验证?IIS具有此功能链接,但到目前为止,我还没有找到自托管端点的等效项.

尽管如此(考虑到这种方法可能不是100%万无一失),我可以通过使用authenticationSchemeSelectorDelegate和OWIN的组合来完成两个步骤.

这将选择适当的AuthenticationScheme(允许包含证书的请求,否则推迟到NTLM身份验证)

public void Configuration(IAppBuilder appBuilder)
{
    var listener = (HttpListener)appBuilder.Properties[typeof(HttpListener).FullName];
    listener.AuthenticationSchemeSelectorDelegate += AuthenticationSchemeSelectorDelegate;
}

private AuthenticationSchemes AuthenticationSchemeSelectorDelegate(HttpListenerRequest httpRequest)
{
    if (!httpRequest.IsSecureConnection) return AuthenticationSchemes.Ntlm;
    var clientCert = httpRequest.GetClientCertificate();
    if (clientCert == null) return AuthenticationSchemes.Ntlm;
    else return AuthenticationSchemes.Anonymous;
}
Run Code Online (Sandbox Code Playgroud)

这将读取cert的内容并相应地填充"server.User"环境变量

public class CertificateAuthenticator
{
    readonly Func<IDictionary<string, object>, Task> _appFunc;

    public CertificateAuthenticator(Func<IDictionary<string, object>, Task> appFunc)
    {
        _appFunc = appFunc;
    }

    public Task Invoke(IDictionary<string, object> environment)
    {
        // Are we authenticated already (NTLM)
        var user = environment["server.User"] as IPrincipal;
        if (user != null && user.Identity.IsAuthenticated) return _appFunc.Invoke(environment);

        var context = environment["System.Net.HttpListenerContext"] as HttpListenerContext;
        if (context == null) return _appFunc.Invoke(environment);

        var clientCertificate = context.Request.GetClientCertificate();

        // Parse out username from certificate

        var identity = new GenericPrincipal
        (
            new GenericIdentity(username), new string[0]
        );

        environment["server.User"] = identity;
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有更好/标准化的方式?

Tra*_*her 3

我还没有看到为此构建的任何标准组件。也就是说,应该可以稍微清理一下你的代码:

  • 您不需要向下转换为 HttpListenerContext 来获取客户端证书。客户端证书应该已在 OWIN 环境中的“ssl.ClientCertificate”下可用。请参阅https://katanaproject.codeplex.com/wikipage?title=OWIN%20Keys。您还需要检查 ssl.ClientCertificateErrors 因为证书可能未通过所有验证检查。
  • 您不需要 AuthenticationSchemeSelectorDelegate 代码。您只需设置 listner.AuthenticationSchemes = NTLM | 匿名的。然后,您在 cert 中间件之后添加一个中间件,如果 server.User 无效,该中间件将返回 401。