【发布时间】:2018-03-25 10:55:00
【问题描述】:
您好,我正在尝试从 HTTPS 网址发出获取请求。但我不断收到错误。
2017-10-13 18:13:43.372427+0800 VQ Smart Home[13412:2155414] Unknown class _TtC13VQ_Smart_Home16ManageUserstable in Interface生成器文件。 2017-10-13 18:13:43.403238+0800 VQ 智能家居 [13412:2155471] TIC SSL 信任错误 [6:0x604000167680]: 3:0 2017-10-13 18:13:43.403672+0800 VQ 智能家居[13412:2155471] NSURLSession/NSURLConnection HTTP 加载失败 (kCFStreamErrorDomainSSL,-9813) 2017-10-13 18:13:43.404000+0800 VQ 智能家居 [13412:2155471] 任务 . HTTP 加载失败(错误 代码:-1202 [3:-9813]) 2017-10-13 18:13:43.404496+0800 VQ 智能家居 [13412:2155472] 任务 . 完成错误 - 代码: -1202 error=Optional(Error Domain=NSURLErrorDomain Code=-1202 "此服务器的证书无效。您可能正在连接到 伪装成“202.73.46.176”的服务器,这可能会将您的 机密信息处于危险之中。” UserInfo={NSURLErrorFailingURLPeerTrustErrorKey=, NSLocalizedRecoverySuggestion=你想 还是连接到服务器?, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9813, NSErrorPeerCertificateChainKey=( “” ), NSUnderlyingError=0x60400025c920 {错误域=kCFErrorDomainCFNetwork 代码=-1202 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, kCFStreamPropertySSLPeerTrust=, _kCFNetworkCFStreamSSLErrorOriginalValue=-9813, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9813, kCFStreamPropertySSLPeerCertificates=( “” )}}, NSLocalizedDescription=此服务器的证书无效。您可能正在连接到假装的服务器 “202.73.46.176”可以将您的机密信息放在 风险。, NSErrorFailingURLKey=https://202.73.46.176/api/v1/user/find/all/1, NSErrorFailingURLStringKey=https://202.73.46.176/api/v1/user/find/all/1, NSErrorClientCertificateStateKey=0})
ViewdidLoad
let urlstr: String = "https://202.73.46.176/api/v1/user/find/all/1"
let request = NSMutableURLRequest(url: NSURL(string: urlstr)! as URL)
request.httpMethod = "GET"
let postString = ""
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
print("response = \(response)")
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("responseString = \(responseString)")
}
task.resume()
方法
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
//Implementation 1: VERY WEAK METHOD
/*if challenge.previousFailureCount > 0{
completionHandler(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil)
}else{
completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust:challenge.protectionSpace.serverTrust!))
}*/
//Implementation 2:
var disposition: URLSession.AuthChallengeDisposition = URLSession.AuthChallengeDisposition.performDefaultHandling
var credential:URLCredential?
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
//certificate-based server credentials are used when verifying the server’s identity
credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
if (credential != nil) {
disposition = URLSession.AuthChallengeDisposition.useCredential
}
else{
disposition = URLSession.AuthChallengeDisposition.performDefaultHandling
}
}
else{
disposition = URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge
}
print("==============", #function," disposition: ", disposition)
print("==============", #function," disposition: ", credential!)
//completionHandler(disposition, credential);
//Implementation 3:
let serverTrust = challenge.protectionSpace.serverTrust
let certificate = SecTrustGetCertificateAtIndex(serverTrust!, 0)
// Set SSL policies for domain name check
let policies = NSMutableArray();
policies.add(SecPolicyCreateSSL(true, (challenge.protectionSpace.host as CFString)))
SecTrustSetPolicies(serverTrust!, policies);
// Evaluate server certificate
var result = SecTrustResultType(rawValue: 0)!
SecTrustEvaluate(serverTrust!, &result)
let isServerTrusted:Bool = (result == SecTrustResultType.unspecified || result == SecTrustResultType.unspecified || result == SecTrustResultType.proceed)
print("==============",#function," isServerTrusted: ", isServerTrusted)
print("==============", #function," result: ", result.hashValue," SecTrustResultType.unspecified: ", SecTrustResultType.unspecified.hashValue," SecTrustResultType.proceed: ", SecTrustResultType.proceed.hashValue)
var certName = ""
// if self.isSimulatingCertificateCorruption {
// certName = corruptedCert
// } else {
// certName = cert
// }
// Get local and remote cert data
let remoteCertificateData = SecCertificateCopyData(certificate!) as Data
let pathToCert = Bundle.main.path(forResource: certName, ofType: "der")
let localCertificate = try! Data(contentsOf: URL(fileURLWithPath: pathToCert!))
print(" remoteCertificateData: ", remoteCertificateData," localCertificate: ", localCertificate, " serverTrust: ", serverTrust.debugDescription )
if ( remoteCertificateData == localCertificate) { //TODO:- this is strictly for tesing puposes, to allow untrusted severs. REMOVE IN PRODUCTION.
let credential:URLCredential = URLCredential(trust: serverTrust!)
completionHandler(.useCredential, credential)
}else if (isServerTrusted && (remoteCertificateData == localCertificate)) {
let credential:URLCredential = URLCredential(trust: serverTrust!)
completionHandler(.useCredential, credential)
} else {
completionHandler(.cancelAuthenticationChallenge, nil)
}
}
谁能帮我修复这个 tnx。
【问题讨论】: