How to use NSURLConnection to connect with SSL for an untrusted cert?
app-transport-security, https, ios, objective-c, ssl-certificate
Solution
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.
Problem
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?
Related problems
- How can I disable ARC for a single file in a project?
- Alternative method for NSURLRequest's private "setAllowsAnyHTTPSCertificate:forHost:"?
- NSURLConnection, NSURLRequest, untrusted cert and user authentication
- Ignoring certificate errors with NSURLConnection
- iOS: Pre install SSL certificate in keychain - programmatically
- Objective-C SSL Synchronous Connection