C# · 2月 22, 2022

c# – 从文件加载客户端证书的HttpClient

我想将相互身份验证添加到在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);

但是当此代码部署到生产Windows 2016 Server计算机时,应用程序将抛出请求已中止:无法创建SSL / TLS安全通道.

我启用了对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,scc = System.Net.SecureCredential)AcquireCredentialsHandle() Failed with error 0X8009030D.Exception in HttpWebRequest#60537518:: – The request was aborted: Could not create SSL/TLS secure channel..

事实证明,此错误是由于缺少IIS用户在PFX文件中读取私钥的权限而导致的.因此,当我将其导入机器证书存储区并通过单击客户端证书上的右键添加IIS_IUSRS时所有任务 – >管理私钥……一切正常,但我想避免这种情况.

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

解决方法 首先,尝试X509KeyStorageFlags.PersistKeySet.接下来我理解你可以使用密钥将其导入密钥存储.如 here所述,您首先应该将密钥导入到商店中(无论是否持久),然后使用密钥.