preventing self signed ssl certificates in ios5

2019-04-17 09:32发布

问题:

I use code that does basic HTTP authentication, see below. This works fine in IOS 5. But now we changed the protocol to https and we used a fake, self signed, certificate. It also worked! This seems insecure. Does anybody know if you need to do something in this method to prevent certain certificates to be accepted?

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:
       (NSURLAuthenticationChallenge *)challenge {

if ([challenge previousFailureCount] <= maxRetryCount ) {
    NSURLCredential *newCredential =
    [NSURLCredential
     credentialWithUser: userName
     password:password
     persistence:NSURLCredentialPersistenceForSession];

    [[challenge sender]
     useCredential:newCredential
     forAuthenticationChallenge:challenge];

   }
   else
   {
     NSLog(@"Failure count %d",[challenge previousFailureCount]);
   }
}

回答1:

It looks I found the answer myself. This blocks the invalid certificates. Still have to test if it works when logging in with a valid certificate.

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:
       (NSURLAuthenticationChallenge *)challenge {

   if ([[[challenge protectionSpace] authenticationMethod] isEqualToString:@"NSURLAuthenticationMethodServerTrust"]) {
      [[challenge sender] performDefaultHandlingForAuthenticationChallenge:challenge];
   }
   else {
      if ([challenge previousFailureCount] <= maxRetryCount ) {
        NSURLCredential *newCredential =
        [NSURLCredential
         credentialWithUser: userName
         password:password
         persistence:NSURLCredentialPersistenceForSession];

        [[challenge sender]
         useCredential:newCredential
         forAuthenticationChallenge:challenge];

       }
       else
       {
         NSLog(@"Failure count %d",[challenge previousFailureCount]);
       }
   }
}


标签: ios ssl https ios5