c# - 使用 HTTPClient 进行双向身份验证

标签 c# authentication ssl ssl-certificate httpclient

我正在尝试对需要双向 SSL 连接(客户端身份验证)的服务器进行 HTTP 调用。我有一个包含多个证书和密码的 .p12 文件。请求使用 Protocol Buffer 进行序列化。

我的第一个想法是将 keystore 添加到 HttpClient 使用的 WebRequestHandler 的 ClientCertificate 属性中。我还在我的计算机上将 keystore 添加到我信任的根证书颁发机构。

当执行 PostAsync 时,我总是收到“无法创建 ssl/tls 安全通道”。显然我做错了什么,但我在这里有点不知所措。

如有任何指点,我们将不胜感激。

    public void SendRequest()
    {
        try
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

            var handler = new WebRequestHandler();

            // Certificate is located in bin/debug folder
            var certificate = new X509Certificate2Collection();
            certificate.Import("MY_KEYSTORE.p12", "PASSWORD", X509KeyStorageFlags.DefaultKeySet);

            handler.ClientCertificates.AddRange(certificate);
            handler.ServerCertificateValidationCallback = ValidateServerCertificate;

            var client = new HttpClient(handler)
            {
                BaseAddress = new Uri("SERVER_URL")
            };
            client.DefaultRequestHeaders.Add("Accept", "application/x-protobuf");
            client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/x-protobuf");
            client.Timeout = new TimeSpan(0, 5, 0);

            // Serialize protocol buffer payload
            byte[] protoRequest;
            using (var ms = new MemoryStream())
            {
                Serializer.Serialize(ms, MyPayloadObject());
                protoRequest = ms.ToArray();
            }

            var result = await client.PostAsync("/resource", new ByteArrayContent(protoRequest));

            if (!result.IsSuccessStatusCode)
            {
                var stringContent = result.Content.ReadAsStringAsync().Result;
                if (stringContent != null)
                {
                    Console.WriteLine("Request Content: " + stringContent);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            throw;
        }
   }

        private bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
                return true;

            Console.WriteLine("Certificate error: {0}", sslPolicyErrors);

            // Do not allow this client to communicate with unauthenticated servers.
            return false;
        }

编辑

我什至没有破解 ValidateServerCertificate。一旦调用 PostAsync,就会抛出异常。协议(protocol)绝对是 TLS v1。

客户端操作系统是 Windows 8.1。服务器是用 Java 编码的(不确定它在什么操作系统上运行。我无权访问它。它是一个黑盒子。)

堆栈跟踪

在 System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult,TransportContext& context) 在 System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar)

没有内部异常。

最佳答案

您是否尝试将安全协议(protocol)更改为Ssl3?无论哪种情况,您都需要将 Expect 属性设置为 true。它会修复你的错误。您可以进一步探索 this link获得更多关于通过客户端证书进行身份验证的知识。

public void SendRequest()
{
    try
    {
        ServicePointManager.Expect100Continue = true;
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;

        var handler = new WebRequestHandler();
        .....
    }
    ..
}

关于c# - 使用 HTTPClient 进行双向身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32770393/

相关文章:

PHP PDO 加密/ssl 数据层

java - cxf 2way ssl not webservice give 无法创建安全的 XMLInputFactory

c# - “InitializeCulture”不是ASP的成员+间接引用了程序集

c# - 捕捉一般异常

authentication - OAuth 2.0 刷新 token 多个选项卡

通过 IIS 在 ASP Classic 中进行 HTTP 身份验证(基本或摘要)

spring-boot - 带有ssl的spring boot kafka,发送消息时出错

c# - LootTable概率分布的简化

c# - Silverlight 套接字中的超时

ios - 使用 twitter swift 4 登录时出错