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

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

问题描述

我正在尝试在适用于iOS 8的WKWebView中加载带有自签名证书的HTTPS网址,但它仍然失败。与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.

Swift:

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

Swift 3:

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

Swift 4:

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

Objective-C

Objective-C

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

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

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