Xamarin Android issue connecting via HTTPS to site with self-signed certificate: “Trust anchor for certification path not found.”

后端 未结 1 1376
耶瑟儿~
耶瑟儿~ 2020-12-03 18:23

I am trying to make HTTPS calls to site that has 2 SSL certificates: a self-signed certificate and a certificate that was signed by the the first certificate. When I use an

相关标签:
1条回答
  • 2020-12-03 18:43

    I was able to get this to work in both Android and iOS.

    iOS was easy, just override ServicePointManager.ServerCertificateValidationCallback:

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

    For Android I used Bruno Caceiro's answer from a similar question and a created Dependency Service.

    In my Xamarin Forms project I added a simple interface:

    public interface IHTTPClientHandlerCreationService
    {
      HttpClientHandler GetInsecureHandler();
    }
    

    And in my Xamarin Android project I implemented the interface:

    [assembly: Dependency(typeof(HTTPClientHandlerCreationService_Android))]
    namespace MyApp.Droid
    {
      public class HTTPClientHandlerCreationService_Android : CollateralUploader.Services.IHTTPClientHandlerCreationService
      {
        public HttpClientHandler GetInsecureHandler()
        {
          return new IgnoreSSLClientHandler();
        }
      }
    
      internal class IgnoreSSLClientHandler : AndroidClientHandler
      {
        protected override SSLSocketFactory ConfigureCustomSSLSocketFactory(HttpsURLConnection connection)
        {
          return SSLCertificateSocketFactory.GetInsecure(1000, null);
        }
    
        protected override IHostnameVerifier GetSSLHostnameVerifier(HttpsURLConnection connection)
        {
          return new IgnoreSSLHostnameVerifier();
        }
      }
    
      internal class IgnoreSSLHostnameVerifier : Java.Lang.Object, IHostnameVerifier
      {
        public bool Verify(string hostname, ISSLSession session)
        {
          return true;
        }
      }
    }
    

    Shared code to correctly set up the HttpClient:

    switch (Device.RuntimePlatform)
    {
      case Device.Android:
        this.httpClient = new HttpClient(DependencyService.Get<Services.IHTTPClientHandlerCreationService>().GetInsecureHandler());
        break;
      default:
        ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
        this.httpClient = new HttpClient(new HttpClientHandler());
        break;
    }
    
    0 讨论(0)
提交回复
热议问题