【问题标题】:Two way authentication with HTTPClient使用 HTTPClient 进行两种身份验证
【发布时间】:2015-09-24 20:33:02
【问题描述】:

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

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

执行 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,就会引发异常。协议肯定是 TLS v1。

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

堆栈跟踪

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

没有内在的例外。

【问题讨论】:

  • .P12 文件中存储的证书的颁发者是谁?服务器信任这样的发行者吗?
  • 它是由我尝试连接的服务器的所有者发布的(他们给了我文件)。
  • ValidateServerCertificate 是否返回truefalse?你可以设置一个断点并检查吗?如果返回 false,sslPolocyErrors 的值是多少?尝试始终从方法中返回true 只是为了测试这是否解决了问题?也许您的本地计算机不信任服务器证书的颁发者?
  • 您确定服务器使用 TLS 1.0 吗?看看SecurityProtocolType enumeration。您可以使用 SSL、TLS1.0、TLS1.1 或 TLS 1.2
  • 我什至没有闯入 ValidateServerCertificate。一旦调用 PostAsync,就会引发异常。至于 SecurityProtocol,我很确定它是 TLS1,但我会再次检查。

标签: c# authentication ssl ssl-certificate httpclient


【解决方案1】:

您是否尝试将您的security protocol 更改为Ssl3?无论哪种情况,您都需要将Expect 属性设置为true。它将修复您的错误。此外,您可以探索this link 以获取有关通过客户端证书进行身份验证的更多知识。

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

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

【讨论】:

  • 感谢您的建议。我确实尝试过,但我仍然遇到与原始帖子中提到的相同的错误。
【解决方案2】:

当我看到这篇文章时,我正试图验证正在使用的安全协议。我发现当我使用不正确的安全协议时,我在 ValidateServerCertificate 之前抛出了一个错误。 (IIS 7.x 默认为 SSL3。)要涵盖要使用的协议的所有基础,您可以定义所有基础。 System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12 | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Ssl3;

【讨论】:

    【解决方案3】:

    我使用与您相同的代码库,但没有使用

    certificate.Import("MY_KEYSTORE.p12", "PASSWORD", X509KeyStorageFlags.DefaultKeySet);
    

    我正在使用X509KeyStorageFlags.UserKeySet

    我也已将根证书安装到 CurrentUser/CA 并且正在为我工​​作。

    【讨论】:

      【解决方案4】:

      你试过下面的代码吗?

      ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);
      

      请在你的代码行之前填写

      handler.ClientCertificates.AddRange(certificate);
      

      【讨论】:

        猜你喜欢
        • 2018-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多