Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable HTTPS GET certificate check in Swift 5

Tags:

https

swift

I try to get the text of a website on my server in Swift 5, which (in my opinion) has a valid RSA SSL certificate (a payed one for my subdomain, not self-signed), but I always get Error 1202 "The certificate for this server is invalid". When I visit the website from Safari, there is no problem. Safari says the certificate is valid.

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()
  }

The function is used this way:

    createRequest(qMes: "", location: "https://user:[email protected]:3452/index.php", method: "GET") { (output) in
        print(output)
    }

I added this to my 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>

As the application is for private usage only, it does not matter if there is a problem with certificate verification, so I want to bypass this error somehow.

I did read in many posts that it's not enough to modify the Info.plist to disable certificate verification, but after trying to modify my code for 10 hard hours, I give up because I'm an absolute beginner in Swift and I didn't get it running.

Strange fact: When running this code in my independent watchOS application (the watch itself, and in the simulator), it fails because of certificate verification, but when running the same code in a Playground, no problem occurs.

I also tried with Alamofire 5, same result.

Could someone help me and modify my code?

like image 811
Chris Avatar asked Dec 26 '19 03:12

Chris


Video Answer


1 Answers

If you really want to ignore the SSL certificate you could, for example, ignore it using a method exposed by the URLSessionDelegate as follows:

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)
    }
}

Remember to set the delegate to self when you create the URLSession in your code. For example, you can set it using this:

let session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil)

I hope it helps

like image 118
SwissMark Avatar answered Oct 19 '22 00:10

SwissMark