_ session: URLSession, didReceive challenge: URLAuthenticationChallenge not being called

I'm trying to implement a Mutual TLS session on my app. I have already implemented a class that extends from URLSessionDelegate, URLSessionDataDelegate

I already have my _ session: URLSession, didReceive challenge: URLAuthenticationChallenge implementation that "works" sometimes, and I say sometimes because is not always being called as it should.

This is my code where I use the dataTask

var urlRequest: URLRequest = setRequestHeaders(with: URLRequest(url: url))
     
    urlRequest.method = .get
     
    let sessionDelegate = MTLSURLSessionDelegate()
     
    sessionDelegate.completionHandler = { [weak self] response in
       // Here I handle my data after
      // didReceive response: URLResponse
     // didCompleteWithError error and didReceive data
    }
     
    let session = URLSession(configuration: .default, delegate: sessionDelegate, delegateQueue: OperationQueue.main) // I have tried with a nil queue
     
    let dataTask = session.dataTask(with: urlRequest)
     
    dataTask.resume()

Like I said, this code is already working but sometimes I can see that the delegate is executing all its data delegate methods without calling _ session: URLSession, didReceive challenge: URLAuthenticationChallenge first

Am I missing something here?

I already have my _ session: URLSession, didReceive challenge: URLAuthenticationChallenge implementation that "works" sometimes, and I say sometimes because is not always being called as it should.

Having a client authentication challenge only being called sporadically is very odd. The first thing that sticks out in my mind is that you need to check with the server side folks to make sure this is setup correctly. The reason I say this is because if you are starting your app from cold launch and you hit an endpoint that expects mutual authentication, and the challenge for NSURLAuthenticationMethodClientCertificate is not presented in your URLSessionDelegate then that seems like an issue with your TLS handshake. Now... having said that, if you are seeing this happen after successfully authenticating with your server, AND using the same TLS session ticket then that is not strange. For example, if you test the same endpoint multiple times during the same app run then URLSession, or rather, Network Framework under the hood is most likely using the first TLS session ticket that you created for performance reasons, which is reasonable.

Matt Eaton
DTS Engineering, CoreOS
meaton3@apple.com
_ session: URLSession, didReceive challenge: URLAuthenticationChallenge not being called
 
 
Q