带有从文件加载的客户端证书的 HttpClient

kla*_*sor 5 c# iis client-certificates dotnet-httpclient mutual-authentication

我想向在 IIS 服务器下运行的客户端 .NET 应用程序添加相互身份验证(它是一个调用另一个 Web 服务的 Web 服务)。客户端应用程序从文件加载客户端证书,并且在我的开发计算机上使用以下代码可以正常工作(我尝试使用 .NET 4.6.2 的 Windows 7 和 Windows 10):

var handler = new WebRequestHandler();
var certificate = new X509Certificate2(clientCertPath); -- PFX file with client cert and private key 
handler.ClientCertificates.Add(certificate);
handler.AuthenticationLevel = AuthenticationLevel.MutualAuthRequired;
client = new HttpClient(handler);
Run Code Online (Sandbox Code Playgroud)

但是,当将此代码部署到生产 Windows 2016 Server 计算机时,应用程序会抛出异常The request was aborted: Could not create SSL/TLS secure channel.

我启用了跟踪,System.Net这是我在日志中看到的

SecureChannel#66407304 - Certificate is of type X509Certificate2 and contains the private key.
AcquireCredentialsHandle(package = Microsoft Unified Security Protocol Provider, intent  = Outbound, scc     = System.Net.SecureCredential)
AcquireCredentialsHandle() failed with error 0X8009030D.
AcquireCredentialsHandle(package = Microsoft Unified Security Protocol Provider, intent  = Outbound, scc     = System.Net.SecureCredential)
AcquireCredentialsHandle() failed with error 0X8009030D.
Exception in HttpWebRequest#60537518:: - The request was aborted: Could not create SSL/TLS secure channel..
Run Code Online (Sandbox Code Playgroud)

事实证明,此错误是由于 IIS 用户缺乏读取 PFX 文件中私钥的权限而引起的。因此,当我将其导入计算机证书存储并IIS_IUSRS通过单击客户端证书上的右键进行添加时All Tasks -> Manage Private Keys...,一切正常,但我想避免这种情况。

有没有办法使用从 Windows Server 上的文件加载的客户端证书,并且不将客户端证书 PFX 文件导入到证书存储中?

Ole*_*g M 1

首先,尝试 X509KeyStorageFlags.PersistKeySet。接下来,据我了解,您可以使用密钥并将其导入密钥存储。如此处所述,您应该首先将密钥导入到存储中(无论是否持久),然后使用该密钥。