0

There is a similar question on stack overflow.

Here is my code which will accept the untrusted server certificate anyway.

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)space
{
    //We can always attempt to authenticate...
    return YES;
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    if ([[challenge protectionSpace] authenticationMethod] == NSURLAuthenticationMethodServerTrust) {
        [[challenge sender] useCredential:[NSURLCredential credentialForTrust:[[challenge protectionSpace] serverTrust]] forAuthenticationChallenge:challenge];
    } else {
      // Other situation
    }
}

However, I want to present an alter view to let the user chose whether or not trust the site.

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:
[[challenge protectionSpace]host] message:@"Do you trust this site?" 
delegate:self cancelButtonTitle:@"No" 
otherButtonTitles:@"Yes", @"Just once", nil];

[alert show];

How can I do that?

Community
  • 1
  • 1
Dragon warrior
  • 1,644
  • 2
  • 24
  • 37

1 Answers1

0

As an example you can save the challenge object to a property and then implement the alertView:clickedButtonAtIndex: delegate method like this (this is for the "trust just once"):

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == alertView.cancelButtonIndex)
    {
        [[self.challenge sender] cancelAuthenticationChallenge:self.challenge];
    }
    else
    {
        [self.challenge.sender useCredential:[NSURLCredential credentialForTrust:self.challenge.protectionSpace.serverTrust] forAuthenticationChallenge:self.challenge];
        self.challenge = nil;
    }
}

If you want to trust always you will need to do some more complex things to save and compare the server certificate data. Or make it simple and unsafe by saving that the server url should always be trusted, which makes you vulnerable to man in the middle attacks.

osanoj
  • 1,035
  • 10
  • 9