Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS canAuthenticateAgainstProtectionSpace method not called every time

Tags:

ios

I am trying to perform SSL certificate validation and have implemented the delegate canAuthenticateAgainstProtectionSpace

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:   (NSURLProtectionSpace*)protectionSpace
{
  OSStatus status = SecTrustEvaluate(protectionSpace.serverTrust, &trustResult);
    if(status == errSecSuccess)
    {
    }
    else
    {
    }
}

However, I notice that this delegate gets called the first time for a given URL, but not for subsequent attempts for the same URL. I thought this had to do with the cached response , so I created the NSURLRequest like the following:

NSURLRequest *request = [[NSURLRequest alloc]
                         initWithURL: [NSURL   URLWithString:_urlString]
                         cachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                         timeoutInterval: 10
                         ];

NSURLConnection *connection = [[NSURLConnection alloc]  initWithRequest:request delegate:self];

This doesn't help either. Any ideas, how I can get canAuthenticateAgainstProtectionSpace method to get called every time?

like image 598
Anna Avatar asked Feb 16 '12 00:02

Anna


2 Answers

The answer above doesn't solve the actual problem. The actual problem here is that an authentication challenge is only being presented the first time a connection is established for that URL while the app is open.

As explained here

A TLS session is processor intensive and Apple doesn't want you to create a new one every time a connection is made to that URL, so they cache one for you. In this case, it's working against you, but you should be able to work around the issue by including a "." character at the end of your host.

In our case, we were trying to establish a connection to a web server containing a certificate issued by an in-house CA. Since we knew the CA wouldn't be trusted on the first connection, we allowed the connection to continue so that the CA could be downloaded. During that connection, we add the "." character to the end of the host. All subsequent connections use the regular URL without the "." character at the end of the host. This ensures that the CA cert we downloaded is validated the first time a "real" connection is made.

like image 142
amundsnw Avatar answered Sep 20 '22 22:09

amundsnw


I solved the problem by adding the following code:

- (void)connection:(NSURLConnection *)connection
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
 [[challenge sender] cancelAuthenticationChallenge:challenge];
}   

The above cancels the authentication challenge and so the delegate canAuthenticateAgainstProtectionSpace gets called every time

like image 36
Anna Avatar answered Sep 18 '22 22:09

Anna