0

我正在尝试实现一个请求:

func makeRequest(urlStr: String) {
    let session = URLSession.shared
    let url = URL(string: urlStr)!
    let task = session.dataTask(with: url, completionHandler: { data, response, error in
        if error != nil {
            print(error)
        }
    })
    task.resume()
}

但我需要安装证书,我生成了证书并手动安装在设备上:

ex +'/BEGIN CERTIFICATE/,/END CERTIFICATE/p' <(echo | openssl s_client -showcerts -connect myDomain.io:8243) -scq > file.crt

在此处输入图像描述 当我提出请求时,我收到此错误:

   - some : Error Domain=NSURLErrorDomain Code=-1202 "The certificate for this server is invalid. You might be connecting to a server that is pretending to be “myDomain.io” which could put your confidential information at risk." UserInfo={NSURLErrorFailingURLPeerTrustErrorKey=<SecTrustRef: 0x281cd4870>, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9813, NSErrorPeerCertificateChainKey=(
     "<cert(0x106002800) s: localhost i: localhost>"
 ), NSUnderlyingError=0x2820acd80 {Error Domain=kCFErrorDomainCFNetwork Code=-1202 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, kCFStreamPropertySSLPeerTrust=<SecTrustRef: 0x281cd4870>, _kCFNetworkCFStreamSSLErrorOriginalValue=-9813, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9813, kCFStreamPropertySSLPeerCertificates=(
     "<cert(0x106002800) s: localhost i: localhost>"
 )}}, NSLocalizedDescription=The certificate for this server is invalid. You might be connecting to a server that is pretending to be “myDomain.io” which could put your confidential information at risk., NSErrorFailingURLKey=https://myDomain.io:8243, NSErrorFailingURLStringKey=https://myDomain.io:8243, NSErrorClientCertificateStateKey=0}

你们中的任何人都知道为什么或如何解决这个问题?或者是否是应用程序识别设备中证书的一种方式?

我会非常感谢你的帮助。

4

1 回答 1

0

使用以下代码进行证书固定。将您的公钥证书添加到应用程序中。

let config = URLSessionConfiguration.default
    let session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
    guard let url1 = URL.init(string: "Your URL") else {
        return
    }
    var request = URLRequest.init(url: url1)
    let task = session?.dataTask(with: request) { (data, response, error) in

    }

    extension yourClassName : URLSessionDelegate {
        public func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
            if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
                if let serverTrust = challenge.protectionSpace.serverTrust {
                    var secresult = SecTrustResultType.invalid
                    let status = SecTrustEvaluate(serverTrust, &secresult)

                    if (errSecSuccess == status) {
                        if let serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0) {
                            let serverCertificateData = SecCertificateCopyData(serverCertificate)
                            let data = CFDataGetBytePtr(serverCertificateData)
                            let size = CFDataGetLength(serverCertificateData)
                            let cert1 = NSData(bytes: data, length: size)
                            var file_der: String?
                            if let certName = "certiifcate Name", let certType = "certicifateType" {
                                file_der = Bundle.main.path(forResource: certName, ofType: certType)
                            }
                            if let file = file_der {
                                if let cert2 = NSData(contentsOfFile: file) {
                                    completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: serverTrust))
                                    return
                                    // }
                                }
                            }
                        }
                    }
                }
            }

            // Pinning failed
            completionHandler(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil)
        }
    }
于 2019-10-04T20:25:44.847 回答