如何在IOS中检查所有NSURLConnection的SSL证书

时间:2013-01-30 07:48:03

标签: ios ssl nsurlconnection

现在我使用-connection:didReceiveAuthenticationChallenge:函数来检查SSL证书。根据用户的要求,我需要检查所有请求。但是在我的测试演示中,-connection:didReceiveAuthenticationChallenge:委托函数将在5分钟内被调用一次。 5分钟后,它将再次被调用。但我们的用户可能会在5分钟内发送多个请求。有人知道有必要解决这个问题吗?

请求代码

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

代表职能:

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

}

1 个答案:

答案 0 :(得分:1)

没有简单的方法来刷新TLS缓存:http://developer.apple.com/library/ios/#qa/qa1727/_index.html

尝试重新考虑您的用例,以确定您是否确实每次都需要身份验证。