证书未与C#http请求一起发送

时间:2020-08-15 13:12:12

标签: c# asp.net-core ssl self-signed

我的问题与以下帖子有关:

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, b, c, d) => { return true; };
// replace it with the below
handler.ServerCertificateValidationCallback = (a, b, c, d) => { return true; };

我可以通过以下方法在ngix服务器上观察到错误:

peer closed connection in SSL handshake while SSL handshaking

我可以在c#端观察到此错误:

Mono.Security.Interface.TlsException: CertificateUnknown

在阅读上述堆栈文章时,我的印象是可以通过修改ServerCertificateValidationCallback来读取和忽略自签名证书。这个实验使我相信不是。我是否错过了使用自签名证书进行https请求的关键步骤?

0 个答案:

没有答案
相关问题