允许使用 WKWebView 自签名证书

Allow self signed certificates using WKWebView

我有以下代码,但我不知道为什么我的 webview 没有加载。

override func viewDidLoad() {
    super.viewDidLoad()
    loadWebview(env_url:"https://myurl.com")
}

func loadWebview(env_url : String){

    let config = WKWebViewConfiguration()
    let controller = WKUserContentController()
    config.userContentController = controller
    //only https is allowed
    let url = URL(string: env_url)
    if let optional_url = url {
        let url_request = URLRequest(url: optional_url)
        webview = WKWebView(frame: self.view.frame, configuration: config)
        webview?.load(url_request)
        webview?.allowsBackForwardNavigationGestures = true
        webview?.navigationDelegate = self
        webview?.uiDelegate = self
        view.addSubview(webview!)

    }
    else{
        showAlertDebug(message: "Invalid URL")
    }
}

extension WebViewController : WKNavigationDelegate {
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping ((WKNavigationActionPolicy) -> Void)) {

    decisionHandler(.allow)
}

func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
    let cred = URLCredential(trust: challenge.protectionSpace.serverTrust!)
    completionHandler(.useCredential, cred)
}
}

extension WebViewController : WKUIDelegate {

}

您必须在 Info.plist 中提供 ATS(应用程序传输安全)例外情况才能覆盖证书验证逻辑。当您接受证书时,ATS 系统仍然拒绝它。有关详细信息,请参阅 Information Property List Key Reference 中的 NSAppTransportSecurity。一般来说,您需要 NSAllowsArbitraryLoadsInWebContent 用于您的特定域。

谨记:

App Store Review for ATS

Your use of certain App Transport Security (ATS) keys triggers additional App Store review for your app, and requires you to provide justification. These keys are:

  • NSAllowsArbitraryLoads
  • NSAllowsArbitraryLoadsForMedia
  • NSAllowsArbitraryLoadsInWebContent
  • NSExceptionAllowsInsecureHTTPLoads
  • NSExceptionMinimumTLSVersion

Some examples of justifications eligible for consideration are:

  • Must connect to a server managed by another entity that does not support secure connections
  • Must support connecting to devices that cannot be upgraded to use secure connections, and that must be accessed via public host names
  • Must provide embedded web content from a variety of sources, but cannot use a class supported by the NSAllowsArbitraryLoadsInWebContent key
  • App loads media content that is encrypted and that contains no personalized information

When submitting your app to the App Store, provide sufficient information for the App Store to determine why your app cannot make secure connections by default.

作为一般规则,获得商业证书比管理您自己的根证书(这才是“自签名”证书的真正含义)的例外情况更容易。