我目前在 Apple Store 上的应用程序具有登录功能。我收到了很多只使用 iPhone 4 的客户的投诉。他们抱怨无法登录自己的帐户。这只发生在 iPhone 4 设备上(也可能是支架设备)。该错误返回一个代码 -1202 (NSURLErrorServerCertificateUntrusted)。我不明白的是它适用于任何较新的设备(iPhone 4S、5、5C 和 5S)。
- (IBAction)didTapButton:(id)sender
{
NSURL *url = [NSURL URLWithString:@"MY_LOGIN_URL"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
#pragma mark - NSURLConnectionDataDelegate
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"Failed");
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response
{
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"Succeded");
}
我知道我可以通过植入下面的行来强制应用程序信任服务器,但这不是一个有效的解决方案。
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
}
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}
如果我添加 didReceiveAuthenticationChallenge 是否足够:
SecTrustRef trustRef = [[challenge protectionSpace] serverTrust];
SecTrustEvaluate(trustRef, NULL);
CFIndex count = SecTrustGetCertificateCount(trustRef);
if(count > 0)
{
SecCertificateRef certRef = SecTrustGetCertificateAtIndex(trustRef, 0);
CFStringRef certSummary = SecCertificateCopySubjectSummary(certRef);
NSString* certSummaryNs = (__bridge NSString*)certSummary;
if([certSummaryNs isEqualToString:@"MY_API"])
NSLog(@"Verified");
else
NSLog(@"Invalid");
}
else
NSLog(@"No certificate found");