Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use NSURLConnection to connect with SSL for an untrusted cert?

I have the following simple code to connect to a SSL webpage

NSMutableURLRequest *urlRequest=[NSMutableURLRequest requestWithURL:url]; [ NSURLConnection sendSynchronousRequest: urlRequest returningResponse: nil error: &error ]; 

Except it gives an error if the cert is a self signed one Error Domain=NSURLErrorDomain Code=-1202 UserInfo=0xd29930 "untrusted server certificate". Is there a way to set it to accept connections anyway (just like in a browser you can press accept) or a way to bypass it?

like image 961
erotsppa Avatar asked Jun 01 '09 02:06

erotsppa


People also ask

What is SSL untrusted?

Untrusted Certificate Authority This error means that the browser cannot find the root certificate in the local trusted certificate store. While establishing the SSL Chain of Trust if the browser cannot find any locally trusted root certificates, then it will not trust the server's certificate.


2 Answers

There is a supported API for accomplishing this! Add something like this to your NSURLConnection delegate:

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {   return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]; }  - (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {   if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])     if ([trustedHosts containsObject:challenge.protectionSpace.host])       [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];    [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge]; } 

Note that connection:didReceiveAuthenticationChallenge: can send its message to challenge.sender (much) later, after presenting a dialog box to the user if necessary, etc.

like image 114
Gordon Henriksen Avatar answered Sep 30 '22 17:09

Gordon Henriksen


If you're unwilling (or unable) to use private APIs, there's an open source (BSD license) library called ASIHTTPRequest that provides a wrapper around the lower-level CFNetwork APIs. They recently introduced the ability to allow HTTPS connections using self-signed or untrusted certificates with the -setValidatesSecureCertificate: API. If you don't want to pull in the whole library, you could use the source as a reference for implementing the same functionality yourself.

like image 35
Nathan de Vries Avatar answered Sep 30 '22 17:09

Nathan de Vries