是否有可能(如果可以,如何?)配置自托管的 owin 端点以使用客户端证书映射身份验证和 A/D? IIS 有这个功能 link ,但到目前为止,我还没有找到自托管端点的等效项。
虽然我使它起作用的方式(记住这种方法可能不是 100% 万无一失的)是一个两步过程,通过结合使用 authenticationSchemeSelectorDelegate 和 OWIN。
这将选择适当的身份验证方案(允许包含证书的请求通过,否则推迟到 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;
}
这将读取证书的内容并相应地填充“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;
}
}
有没有更好/标准化的方式?
最佳答案
我还没有看到为此构建的任何标准组件。也就是说,应该可以稍微清理一下您的代码:
- 您无需向下转换为 HttpListenerContext 即可获取客户端证书。客户端证书应该已经在“ssl.ClientCertificate”下的 OWIN 环境中可用。参见 https://katanaproject.codeplex.com/wikipage?title=OWIN%20Keys .您还需要检查 ssl.ClientCertificateErrors,因为该证书可能未通过所有验证检查。
- 您不需要 AuthenticationSchemeSelectorDelegate 代码。您可以只设置 listner.AuthenticationSchemes = NTLM |匿名的。然后,您在证书中间件之后添加一个中间件,如果 server.User 无效,该中间件将返回 401。
关于c# - 自托管 Owin 端点中的客户端证书映射身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19831769/