最近在项目中使用WKWebView加载https链接的时候遇到一些证书验证的问题,就研究了一下
- 先说说我遇到的问题:
"The certificate for this server is invalid. You might be connecting to a server
that is pretending to be “xxx.xxx.com” which could put your confidential
information at risk."
意思是说“这个服务器的证书是无效的。你可能会连接到一个服务器,
它是伪装“xxx.xxx.com”,可以把您的机密信息处于危险之中。”
客户端信任证书的过程:
1.当客户端要访问服务器的时候,服务器向客户端发送受保护的信任证书
2.客户端判断是否对客户端发送的证书进行信任,,
3.如果信任.则客户端会安装公钥在客户端,而服务器就拥有受保护证书的密钥,每一次向服务器请求数据的时候,服务器会先将要发送的数据进行密钥加密,客户端对所传数据通过公钥解密
上面遇到的问题,有两种解决方法:
1、在WKNavigationDelegate的代理方法中实现信任证书
func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void) {
// 判断是否是信任服务器证书
if challenge.protectionSpace.authenticationMethod
== NSURLAuthenticationMethodServerTrust {
// 告诉服务器,客户端信任证书
// 创建凭据对象
let card = URLCredential.init(trust: challenge.protectionSpace.serverTrust!)
// 告诉服务器信任证书
completionHandler(URLSession.AuthChallengeDisposition.useCredential, card)
}
}
2、让服务器更换服务器上的证书(当然这是最合理的一种方式)
- 如有错误欢迎指出
不懂就药问
网友评论