Pages

Wednesday, November 16, 2011

[Code Snippet] Accesing to SSL server trust web services

This code snippet completes the two previous post that says how to connect to a REST service and consume it synchronous and asynchronously.

When we have to access a HTTPS web service first thing that we should think is how to store the trusted root certificate in our iPhone or iPad. Our device has installed some of the most used certificates (you can check the list here) and for this snippet we asume that the server uses Verisign, GoDaddy or any other common SSL certificate, so we have yet installed it.

To accomplish this task you should implement the next functions of NSURLConnection delegate:


- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection
{
    return TRUE;}
-(void)connection:(NSURLConnection *)connection didCancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    NSLog(@"Challenge cancelled");}
-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
   // Server Trust authentication method
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
  
    //Here we told the OS that validate the server certificate against our credential storage.
    [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];       
    NSLog(@"Reto superado");}

If we just want to bypass the authentication, instead of useCredential, we should use continueWithoutCredential method in didReceiveAuthenticationChallenge.

    //Bypass without credentials
    [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];

I hope this code snippet could be useful for you, enjoy it!

NOTE: This can be used only with NSURLConnection, just for asynchronous request.

No comments:

Post a Comment