在 Swift 5 中禁用 HTTPS GET 证书检查

Chr*_*ris 5 https swift

我尝试使用 Swift 5 在我的服务器上获取网站的文本,它(在我看来)具有有效的 RSA SSL 证书(为我的子域付费,而不是自签名),但我总是收到错误 1202“此服务器的证书无效”。当我从 Safari 访问网站时,没有问题。Safari 说证书有效。

public func createRequest(qMes: String, location: String, method: String , completionBlock: @escaping (String) -> Void) -> Void
  {

      let requestURL = URL(string: location)
      var request = URLRequest(url: requestURL!)

      request.httpMethod = method
      request.httpBody = qMes.data(using: .utf8)

      let requestTask = URLSession.shared.dataTask(with: request) {
          (data: Data?, response: URLResponse?, error: Error?) in

          if(error != nil) {
              print("Error: \(error)")
          }else
          {

            let outputStr  = String(data: data!, encoding: String.Encoding.utf8) as String?
              completionBlock(outputStr!);
          }
      }
      requestTask.resume()
  }
Run Code Online (Sandbox Code Playgroud)

该函数是这样使用的:

    createRequest(qMes: "", location: "https://user:password@subdomain.server.com:3452/index.php", method: "GET") { (output) in
        print(output)
    }
Run Code Online (Sandbox Code Playgroud)

我将此添加到我的 Info.plist

<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSExceptionDomains</key>
        <dict>
            <key>server.com</key>
            <dict>
                <key>NSExceptionAllowsInsecureHTTPLoads</key>
                <true/>
                <key>NSExceptionRequiresForwardSecrecy</key>
                <false/>
                <key>NSIncludesSubdomains</key>
                <true/>
            </dict>
        </dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
        <key>NSAllowsLocalNetworking</key>
        <true/>
    </dict>
Run Code Online (Sandbox Code Playgroud)

由于该应用程序仅供私人使用,因此证书验证是否存在问题并不重要,因此我想以某种方式绕过此错误。

我确实在很多帖子中读到过修改Info.plist以禁用证书验证是不够的,但是在尝试修改我的代码 10 个小时后,我放弃了,因为我是 Swift 的绝对初学者并且我没有让它运行.

奇怪的事实:在我的独立 watchOS 应用程序(手表本身和模拟器中)中运行此代码时,由于证书验证而失败,但是在 Playground 中运行相同的代码时,没有出现任何问题。

我也试过 Alamofire 5,结果一样。

有人可以帮助我并修改我的代码吗?

小智 11

例如,如果您真的想忽略 SSL 证书,则可以使用以下公开的方法忽略它URLSessionDelegate

extension YOURVIEWCONTROLLER: URLSessionDelegate {
    public func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
       //Trust the certificate even if not valid 
       let urlCredential = URLCredential(trust: challenge.protectionSpace.serverTrust!)

       completionHandler(.useCredential, urlCredential)
    }
}
Run Code Online (Sandbox Code Playgroud)

请记住在代码中self创建时将委托设置为URLSession。例如,您可以使用以下方法设置它:

let session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil)
Run Code Online (Sandbox Code Playgroud)

我希望它有帮助