Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS 5 NSURLConnection to HTTPS Servers

I have searched for hours regarding the NSURLConnection delegates/methods that allows me to use to connect to any HTTPS servers. Even I searched on this site and I found answers, answers which didn't work for me.

I will upload the code link if any of you want me to. But I would prefer a tutorial / sample codes / source code of a simple UIWebView connecting to any HTTPS Servers. And I will take it from there.

Thanks in advance.

like image 792
Melvin Lai Avatar asked Feb 03 '12 01:02

Melvin Lai


1 Answers

Whether you are connecting to a HTTPS or HTTP site should be completely transparent both for NSURLConnection and for UIWebView controls. The only thing you may need to do is, if the server sites certificate is a self-signed or non-verifiable certificate, add code to bypass the authentication challenge that the browser gets. (i.e. the equivalent of the message that the certificate is signed by an unknown authority and do you want to accept it).

Just use a @"https://www.myhttpsite.com/" URL and it should work the same way as normal HTTP urls.

To bypass the security issue of an unrecognised certificate signer, for an NSURLConnection, add the following to your delegate methods:

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    NSArray *trustedHosts = [NSArray arrayWithObjects:@"mytrustedhost",nil];

    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];
}

In pre iOS4.3 you need to do something a bit different, you can add a category to the URLRequest class that implements security bypass for certificates from an unrecognised host.

Note be careful with any solution that ignores that a certificate isn't signed by a recognised authority as you are opening up a potential security hole when doing it, but it often is necessary at least for testing against a test server that has self/internally signed certificate on it.

To open a URL connection in a web view:

NSURL *websiteUrl = [NSURL URLWithString:@"https://www.mysecuresite.com/"];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:websiteurl];
[myWebView loadRequest:urlRequest];
like image 168
gamozzii Avatar answered Sep 28 '22 08:09

gamozzii