Tao Fang
Tao Fang

Reputation: 113

How to check SSL certificate in IOS for all the NSURLConnections

Now I use -connection:didReceiveAuthenticationChallenge: function to check the SSL certificate. Based on the user's requirement, I need to check all the requests. But in my test demo, the -connection:didReceiveAuthenticationChallenge: delegate function will be called only once in 5 mins. After 5 mins, it will be called again. But our user may send more than one request in 5 mins. Is any one know have to solve this problem?

The request code

NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:_server_url]];
[urlRequest setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:[query dataUsingEncoding:NSUTF8StringEncoding]];

urlConnection = [[[NSURLConnection alloc] initWithRequest:urlRequest delegate:self] autorelease] ;
[urlConnection scheduleInRunLoop:[NSRunLoop mainRunLoop]
                      forMode:NSDefaultRunLoopMode];
[urlConnection start];

Delegate functions:

- (BOOL)connection:(NSURLConnection *)conn canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
    NSLog(@"authenticate method:%@",protectionSpace.authenticationMethod);

    return YES;
}

- (void) connection:(NSURLConnection *)conn didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge 
{
    NSURLAuthenticationChallenge *_challenge=[challenge retain];

    SecTrustRef trustRef = [[_challenge protectionSpace] serverTrust];
    SecTrustEvaluate(trustRef, NULL);

    SecCertificateRef certRef = SecTrustGetCertificateAtIndex(trustRef, 0);

    NSData *certificateData = (NSData *) SecCertificateCopyData(certRef);
    const unsigned char *certificateDataBytes = (const unsigned char *)[certificateData bytes];
    X509 *certificateX509 = d2i_X509(NULL, &certificateDataBytes, [certificateData length]);

    NSString *subject = CertificateGetDomainName(certificateX509);

    NSLog(@"Subject: %@", subject);

    [[_challenge sender] continueWithoutCredentialForAuthenticationChallenge:_challenge];

}

Upvotes: 0

Views: 3256

Answers (1)

MrTJ
MrTJ

Reputation: 13192

There is no simple way to flush the TLS cache: http://developer.apple.com/library/ios/#qa/qa1727/_index.html

Try to rethink your use case to determine whether you really need the authentication every time.

Upvotes: 1

Related Questions