如何解决证书未与C#http请求一起发送
我的问题与以下帖子有关:
HttpClient does not send client certificate on Windows using .NET Core
WebApi HttpClient not sending client certificate
我的环境:
Mac osx(10.15.6)
适用于Mac的Visual Studio代码(8.3.2)
目标:
我想使用自签名证书(作为实验),以使用c#和nginx服务器测试TLS。我可以使用以下curl命令来确认crt和key允许我访问资源:
curl --cert client.crt --key client.key -k https://localhost:443
我使用此代码阅读了p12密钥库
public X509Certificate2 readCertificates(String path,String password)
{
return new X509Certificate2(File.ReadAllBytes(path),password);
}
我使用此代码发出Https请求。加载的证书具有我期望的主题,标识符和私钥。这确认了上面的步骤。
public async System.Threading.Tasks.Task validateRequest(X509Certificate2 certificate)
{
try
{
WebRequestHandler handler = new WebRequestHandler();
handler.ClientCertificates.Add(certificate);
handler.SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls;
ServicePointManager.ServerCertificateValidationCallback = (a,b,c,d) => { return true; };
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
HttpClient client = new HttpClient(handler);
HttpRequestMessage httpContent = new HttpRequestMessage(HttpMethod.Get,new Uri("https://localhost:443"));
HttpResponseMessage response = await client.SendAsync(httpContent);
string resultContent = response.Content.ReadAsStringAsync().Result;
if (response.IsSuccessStatusCode)
{
Console.WriteLine("## we authenticated...");
}
else {
Console.WriteLine("### we have an issue");
}
response.Dispose();
client.Dispose();
httpContent.Dispose();
}
catch (Exception e) {
Console.WriteLine("##### error:: " + e);
}
}
执行此代码后,我的ngix服务器指出:
client sent no required SSL certificate while reading client request header
c#端将$ resultContent $评估为:
400 No required SSL certificate was sent
如果我替换以下几行,则会收到另一个错误:
// take this line
ServicePointManager.ServerCertificateValidationCallback = (a,d) => { return true; };
// replace it with the below
handler.ServerCertificateValidationCallback = (a,d) => { return true; };
我可以通过以下方法在ngix服务器上观察到错误:
peer closed connection in SSL handshake while SSL handshaking
我可以在c#端观察到此错误:
Mono.Security.Interface.TlsException: CertificateUnknown
在阅读上述堆栈文章时,我的印象是可以通过修改ServerCertificateValidationCallback来读取和忽略自签名证书。这个实验使我相信不是。我是否错过了使用自签名证书进行https请求的关键步骤?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。