在 WKWebView 中允许未经验证的 ssl 证书 [英] Allow unverified ssl certificates in WKWebView

查看:118
本文介绍了在 WKWebView 中允许未经验证的 ssl 证书的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 iOS 8 的 WKWebView 中加载带有自签名证书的 HTTPS url,但它一直失败.与 UIWebView 一起使用的解决方法(使用 NSUrlRequest 中的 setAllowsAnyHTTPSCertificate)似乎不起作用.有谁知道任何解决方法?

I'm trying to load a HTTPS url with an self-signed certificate in a WKWebView for iOS 8 and it keeps failing. The workaround used with UIWebView (using setAllowsAnyHTTPSCertificate from NSUrlRequest) doesn't seem to work. Does anyone know of any workaround?

我不需要对 AppStore 有效的解决方案,因为我只需要在开发阶段访问自签名证书站点,而不是在生产阶段,但这对于开发和测试服务器实例来说确实是个问题.

I do not need a solution that is valid for AppStore, as I only need to access self-signed certificate sites on development phases, not on production, but it's really a problem for development and testing server instances.

提前谢谢你.

推荐答案

这在 iOS 9 中已修复!WKWebView 最终在 WKNavigationDelegate 上调用 webView(_:didReceiveAuthenticationChallenge:completionHandler:).不幸的是,如果您在 iOS 8 设备上运行内置于 Xcode 7 的代码,这将不起作用(至少在我的初始测试中没有).

This is fixed in iOS 9! WKWebView finally makes calls to webView(_:didReceiveAuthenticationChallenge:completionHandler:) on WKNavigationDelegate. Unfortunately this does not work if you run code built in Xcode 7 on iOS 8 devices (at least not in my initial testing).

在下面的示例中,我实际上并没有对证书做任何事情,只是让它通过而不做任何进一步的验证(对于生产代码来说显然是一个糟糕的计划).请参阅 Apple 的文档(清单 3)了解他们希望您在此处执行的操作的更多详细信息.

In my example below, I'm not actually doing anything with the cert and just letting it pass through without doing any further validation (obviously a bad plan for production code). See Apple's docs (Listing 3) for more details of what they want you to do here.

斯威夫特:

func webView(webView: WKWebView, didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge,
    completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
        let cred = NSURLCredential.init(forTrust: challenge.protectionSpace.serverTrust!)
        completionHandler(.UseCredential, cred)
}

斯威夫特 3:

let cred = URLCredential(trust: challenge.protectionSpace.serverTrust!)
completionHandler(.useCredential, cred)

斯威夫特 4:

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

目标-C

NSURLCredential * credential = [[NSURLCredential alloc] initWithTrust:[challenge protectionSpace].serverTrust];
completionHandler(NSURLSessionAuthChallengeUseCredential, credential);

这篇关于在 WKWebView 中允许未经验证的 ssl 证书的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆