Xamarin WKWebView Accepting Self-Signed Certificates

后端 未结 1 1162
栀梦
栀梦 2021-01-03 17:22

I have seen various example online saying how to accept them but I always get An SSL error has occurred and a secure connection to the server cannot be made.

1条回答
  •  一生所求
    2021-01-03 18:03

    To support self-signed certs you have two things to do:

    1. Allow NSExceptionAllowsInsecureHTTPLoads on your self-signed domain
      • Even though you are using https, your app is flagged as having a trust issue
    2. Bypass certificate security checking

    Security Note on 2: Get a CA-issued certificate for any production apps as this completely disables certificate validation on your domain and thus allowing MITM attacks, DNS redirection spoofing of your app, etc... You could pin the cert by including the public cer in the main bundle and checking it against the cert received, but that just means a fake certificate would need to be generated in either the MITM or DNS spoofing attack (and tools for those already exist in the various exploit kits)

    Example using the https://badssl.com site:

    WKNavigationDelegate:

    public class NavigationDelegate : WKNavigationDelegate
    {
        const string host = "self-signed.badssl.com";
        public override void DidReceiveAuthenticationChallenge(WKWebView webView, NSUrlAuthenticationChallenge challenge, Action completionHandler)
        {
            switch (challenge.ProtectionSpace.Host)
            {
                case host:
                    using (var cred = NSUrlCredential.FromTrust(challenge.ProtectionSpace.ServerSecTrust))
                    {
                        completionHandler.Invoke(NSUrlSessionAuthChallengeDisposition.UseCredential, cred);
                    }
                    break;
                default:
                    completionHandler.Invoke(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, null);
                    break;
            }
        }
    }
    

    Note: Assign an instance of this class to the NavigationDelegate or WeakNavigationDelegate of your WKWebView instance.

    Info.plist NSAppTransportSecurity:

    NSAppTransportSecurity
    
        NSExceptionDomains
        
            self-signed.badssl.com
            
                NSExceptionAllowsInsecureHTTPLoads
                
            
        
    
    

    0 讨论(0)
提交回复
热议问题