2

I am trying to connect to my ASP.NET Core API which I am running on my other computer. I want to try to add data using a POST request. I am getting these error messages:

Connection 6: default TLS Trust evaluation failed(-9813)

Connection 6: TLS Trust encountered error 3:-9813

Connection 6: encountered error(3:-9813)

The error description is:

The certificate for this server is invalid. You might be connecting to a server that is pretending to be “192.168.0.100” which could put your confidential information at risk.

let jsonData = try? JSONSerialization.data(withJSONObject: data)

let url = URL(string: "https://192.168.0.100:5001/api/Trips")!

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = jsonData

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, error  == nil else {
        print(error?.localizedDescription)
        return
    }

    let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])

    if let responseJSON = responseJSON as? [String: Any] {

    }

}

task.resume()

I am not concerned with any risk at the moment, because this is just for developing purposes. Is there a way to trust the connection or to ignore the check completely?

ivan.vliza
  • 153
  • 3
  • 14
  • if your are using localhost, you don't need to add https, because you don't have a trust certificate, do you?, it's necessary activate ATS (https://stackoverflow.com/questions/31254725/transport-security-has-blocked-a-cleartext-http) – Andres Gomez Nov 29 '19 at 15:22
  • You need to connect same network with which your other computer is connected and use url with http instead of https - "http://192.168.0.100:5001/api/Trips" – Chaman Sharma Nov 29 '19 at 15:29
  • I am still getting the same error. I added a lot of IPs to the info.plist https://i.ibb.co/8rWdk0x/image.png. I also changed the URL string to http 192.168.0.100:5000/api/Trips – ivan.vliza Nov 29 '19 at 15:50
  • Do you have any HTTP interceptor enable? – Mojtaba Hosseini Nov 29 '19 at 17:08
  • No, I don't even know what that is – ivan.vliza Nov 29 '19 at 17:11

2 Answers2

4

I finally figured it out.

I added these lines to my info.plist: INFO.PLIST

I created my session object with these settings:

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

And I added this extension to the bottom of my code:

extension MyViewController : URLSessionDelegate {

    func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
    }

}

Don't forget to remove this for security when deploying your app.

I hope I helped this helped someone. Thanks everyone for your suggestions. This is what my code looks like now:

import UIKit

class MyViewController: UIViewController {

    @IBOutlet weak var createButton: UIBarButtonItem!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func createButtonTapped(_ sender: Any) {

        let data: [String: Any] = ["data1": data1, "data2": data2......]

        let jsonData = try? JSONSerialization.data(withJSONObject: data)

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

        let url = URL(string: "https://192.168.0.100:5001/api/Trips")!

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = jsonData
        request.addValue("application/json",forHTTPHeaderField: "Content-Type")
        request.addValue("application/json",forHTTPHeaderField: "Accept")

        let task = session.dataTask(with: request) { data, response, error in
            guard let data = data, error  == nil else {
                print(error?.localizedDescription)
                return
            }

            let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])

            if let responseJSON = responseJSON as? [String: Any] {
                .....
            }

        }

        task.resume()
    }
}


extension MyViewController : URLSessionDelegate {

    func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
    }

}
ivan.vliza
  • 153
  • 3
  • 14
  • 1
    You’re connecting to a host by IP, which will never pass a TLS check, because there’s no way for the networking stack to know the hostname. If this is for internal testing, you can write a custom handler similar to what you wrote, but perform your own certificate validation, substituting a different hostname for validation purposes. Apple has a doc called “Overriding TLS chain validation correctly” that contains an example of how to do this. Please don’t leave validation fully disabled, even temporarily, because those sorts of hacks tend to accidentally ship. :-) – dgatwood Dec 03 '19 at 21:35
1

All you need to set these property in info.plist

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
    <key>NSExceptionDomains</key>
    <dict>
        <key>example.com</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSIncludesSubdomains</key>
            <true/>
        </dict>
    </dict>
</dict>