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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With