是否可以通过HttpClient在HTTP请求期间禁用客户端证书验证?
我们希望通过正面和负面测试来测试客户证书的有效性。因此,在某些情况下,我们希望发送无效的客户端证书(过期,无效等)。但是,使用此类客户端证书时,无法将请求发送到目标API或目标API上的客户端证书为空。
客户端发送HTTP请求
var handler = new HttpClientHandler();
var certificateNotValid = new X509Certificate2(@"C:\src\test.pfx", "pass");
handler.ClientCertificates.Add(CertificateNotValid);
var client = new HttpClient(handler);
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "https://url");
var result = await client.SendAsync(httpRequestMessage);
如果从路径读取证书为
var certificateNotValid = new X509Certificate2(@"C:\src\test.pfx", "password");
,
HTTP请求客户端抛出System.Net.Http.HttpRequestException: 'An error occurred while sending the request.'. Win32Exception: The received certificate has expired
。
如果从Windows证书存储中读取的证书为
X509Certificate2 certificate;
using (var store = new X509Store(StoreName.Root, StoreLocation.LocalMachine))
{
store.Open(OpenFlags.ReadOnly);
var certificates = store.Certificates.Find(X509FindType.FindBySubjectName, cn, false);
certificate = certificates[0];
store.Close();
}
目标API获取空客户端证书。
添加服务器证书验证调用没有帮助(在HTTP客户端和目标API上)。
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, x509Chain, errors) => { return true; };
目标API将客户端证书读取为
var clientCertificate = await context.Connection.GetClientCertificateAsync();