允许使用HttpClient的不受信任的SSL证书

时间:2012-09-23 14:45:01

标签: c# .net windows-8 windows-runtime

我很难让我的Windows 8应用程序通过SSL与我的测试Web API进行通信。

似乎HttpClient / HttpClientHandler没有提供和选项来忽略像WebRequest这样的不受信任的证书(虽然以“hacky”方式使用ServerCertificateValidationCallback)。

非常感谢任何帮助!

12 个答案:

答案 0 :(得分:124)

快速而肮脏的解决方案是使用ServicePointManager.ServerCertificateValidationCallback代理。这允许您提供自己的证书验证。验证在整个App域中全局应用。

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

我主要用于单元测试,我希望针对我正在托管的端点运行并尝试使用WCF clientHttpClient点击它。

对于生产代码,您可能需要更精细的控制,最好使用WebRequestHandler及其ServerCertificateValidationCallback委托属性(请参阅dtb's answer below)。或使用answer ctacke HttpClientHandler。我现在更喜欢这两个中的任何一个,即使我使用我的过去的集成测试,除非我找不到任何其他钩子。

答案 1 :(得分:72)

查看WebRequestHandler Class及其ServerCertificateValidationCallback Property

using (var handler = new WebRequestHandler())
{
    handler.ServerCertificateValidationCallback = ...

    using (var client = new HttpClient(handler))
    {
        ...
    }
}

答案 2 :(得分:24)

如果您尝试在.NET标准库中执行此操作,这是一个简单的解决方案,具有在您的处理程序中返回true的所有风险。我把安全留给你。

var handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ServerCertificateCustomValidationCallback = 
    (httpRequestMessage, cert, cetChain, policyErrors) =>
{
    return true;
};

var client = new HttpClient(handler);

答案 3 :(得分:21)

或者您可以在Windows.Web.Http命名空间中使用 HttpClient

var filter = new HttpBaseProtocolFilter();
#if DEBUG
    filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Expired);
    filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
    filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);
#endif
using (var httpClient = new HttpClient(filter)) {
    ...
}

答案 4 :(得分:11)

使用Windows 8.1,您现在可以信任无效的SSL证书。您必须使用Windows.Web.HttpClient,或者如果您想使用System.Net.Http.HttpClient,您可以使用我写的消息处理程序适配器: http://www.nuget.org/packages/WinRtHttpClientHandler

Docs在GitHub上: https://github.com/onovotny/WinRtHttpClientHandler

答案 5 :(得分:6)

如果这是针对Windows运行时应用程序的,那么您必须将自签名证书添加到项目中并在appxmanifest中引用它。

文档在这里: http://msdn.microsoft.com/en-us/library/windows/apps/hh465031.aspx

如果它来自不受信任的CA(如机器本身不信任的私有CA),则需要获取CA的公共证书,将其作为内容添加到应用程序,然后将其添加到清单。

完成后,应用程序会将其视为正确签名的证书。

答案 6 :(得分:3)

这里的大多数答案都建议使用典型模式:

using (var httpClient = new HttpClient())
{
 // do something
}

因为有IDisposable接口。 请不要!

Microsoft告诉您原因:

在这里您可以找到详细的分析幕后情况: https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/

关于您的SSL问题,并基于https://docs.microsoft.com/en-us/azure/architecture/antipatterns/improper-instantiation/#how-to-fix-the-problem

这是您的模式:

class HttpInterface
{
 // https://docs.microsoft.com/en-us/azure/architecture/antipatterns/improper-instantiation/#how-to-fix-the-problem
 // https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient#remarks
 private static readonly HttpClient client;

 // static initialize
 static HttpInterface()
 {
  // choose one of these depending on your framework

  // HttpClientHandler is an HttpMessageHandler with a common set of properties
  var handler = new HttpClientHandler();
  {
      ServerCertificateCustomValidationCallback = delegate { return true; },
  };
  // derives from HttpClientHandler but adds properties that generally only are available on full .NET
  var handler = new WebRequestHandler()
  {
      ServerCertificateValidationCallback = delegate { return true; },
      ServerCertificateCustomValidationCallback = delegate { return true; },
  };

  client = new HttpClient(handler);
 }

 .....

 // in your code use the static client to do your stuff
 var jsonEncoded = new StringContent(someJsonString, Encoding.UTF8, "application/json");

 // here in sync
 using (HttpResponseMessage resultMsg = client.PostAsync(someRequestUrl, jsonEncoded).Result)
 {
  using (HttpContent respContent = resultMsg.Content)
  {
   return respContent.ReadAsStringAsync().Result;
  }
 }
}

答案 7 :(得分:2)

我没有答案,但我确实有另一种选择。

如果您使用Fiddler2来监控流量并启用HTTPS解密,则您的开发环境不会抱怨。这不适用于WinRT设备,例如Microsoft Surface,因为您无法在其上安装标准应用程序。但是你的开发Win8计算机会很好。

要在Fiddler2中启用HTTPS加密,请转到工具>提琴手选项> HTTPS(标签)>选中“解密HTTPS流量”

我将继续关注这个线索,希望有人有一个优雅的解决方案。

答案 8 :(得分:2)

如果您使用的是System.Net.Http.HttpClient,我相信正确的格式是

var handler = new HttpClientHandler() 
{ 
    ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
};

var http = new HttpClient(handler);
var res = http.GetAsync(url);

答案 9 :(得分:1)

我在网上找到了一个似乎运作良好的例子:

首先,您要创建一个新的ICertificatePolicy

using System.Security.Cryptography.X509Certificates;
using System.Net;

public class MyPolicy : ICertificatePolicy
{
  public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request, 
int certificateProblem)
  {
    //Return True to force the certificate to be accepted.
    return true;
  }
}

然后在发送您的http请求之前使用它,如下所示:

System.Net.ServicePointManager.CertificatePolicy = new MyPolicy();

http://www.terminally-incoherent.com/blog/2008/05/05/send-a-https-post-request-with-c/

答案 10 :(得分:0)

我在此Kubernetes client中找到了一个示例,其中他们使用X509VerificationFlags.AllowUnknownCertificateAuthority来信任自签名自签名根证书。我稍微修改了他们的示例,以使用我们自己的PEM编码的根证书。希望这对某人有帮助。

namespace Utils
{
  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Net.Security;
  using System.Security.Cryptography.X509Certificates;

  /// <summary>
  /// Verifies that specific self signed root certificates are trusted.
  /// </summary>
  public class HttpClientHandler : System.Net.Http.HttpClientHandler
  {
    /// <summary>
    /// Initializes a new instance of the <see cref="HttpClientHandler"/> class.
    /// </summary>
    /// <param name="pemRootCerts">The PEM encoded root certificates to trust.</param>
    public HttpClientHandler(IEnumerable<string> pemRootCerts)
    {
      foreach (var pemRootCert in pemRootCerts)
      {
        var text = pemRootCert.Trim();
        text = text.Replace("-----BEGIN CERTIFICATE-----", string.Empty);
        text = text.Replace("-----END CERTIFICATE-----", string.Empty);
        this.rootCerts.Add(new X509Certificate2(Convert.FromBase64String(text)));
      }

      this.ServerCertificateCustomValidationCallback = this.VerifyServerCertificate;
    }

    private bool VerifyServerCertificate(
      object sender,
      X509Certificate certificate,
      X509Chain chain,
      SslPolicyErrors sslPolicyErrors)
    {
      // If the certificate is a valid, signed certificate, return true.
      if (sslPolicyErrors == SslPolicyErrors.None)
      {
        return true;
      }

      // If there are errors in the certificate chain, look at each error to determine the cause.
      if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) != 0)
      {
        chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;

        // add all your extra certificate chain
        foreach (var rootCert in this.rootCerts)
        {
          chain.ChainPolicy.ExtraStore.Add(rootCert);
        }

        chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
        var isValid = chain.Build((X509Certificate2)certificate);

        var rootCertActual = chain.ChainElements[chain.ChainElements.Count - 1].Certificate;
        var rootCertExpected = this.rootCerts[this.rootCerts.Count - 1];
        isValid = isValid && rootCertActual.RawData.SequenceEqual(rootCertExpected.RawData);

        return isValid;
      }

      // In all other cases, return false.
      return false;
    }

    private readonly IList<X509Certificate2> rootCerts = new List<X509Certificate2>();
  }
}

答案 11 :(得分:0)

对于Xamarin Android,这是唯一适用于我的解决方案:another stack overflow post

如果您使用的是AndroidClientHandler,则需要提供SSLSocketFactoryHostnameVerifier的自定义实现,并禁用所有检查。为此,您需要继承AndroidClientHandler的子类并覆盖适当的方法。

internal class BypassHostnameVerifier : Java.Lang.Object, IHostnameVerifier
{
    public bool Verify(string hostname, ISSLSession session)
    {
        return true;
    }
}
 
internal class InsecureAndroidClientHandler : AndroidClientHandler
{
    protected override SSLSocketFactory ConfigureCustomSSLSocketFactory(HttpsURLConnection connection)
    {
        return SSLCertificateSocketFactory.GetInsecure(1000, null);
    }
 
    protected override IHostnameVerifier GetSSLHostnameVerifier(HttpsURLConnection connection)
    {
        return new BypassHostnameVerifier();
    }
}

然后

var httpClient = new System.Net.Http.HttpClient(new InsecureAndroidClientHandler());