我想在自定义iOS 6应用中使用HTTPS访问一些网络资源。某些目标服务器正在使用由CA签名的证书,该证书默认情况下不包含在iOS中,而是手动添加到设备的钥匙串中。因此,可以在Safari中打开所有URL,而不会发出任何警告或错误。
我想要实现的是与Safari相同的行为:我希望加载网站,如果Safari会信任它们,或者在发生任何错误时拒绝加载它们。由于安装的证书可以根据具体情况而变化我不想要在应用程序资源中手动包含任何证书,这就是SO的许多问题。
我的问题是我没有SecTrustEvaluate
返回 kSecTrustResultProceed 。你知道我能做什么吗?
如果我的canAuthenticateAgainstProtectionSpace
返回否,iOS会自行处理服务器证书检查,但似乎没有检查额外安装的证书(如Safari所做的那样)。
以下是一些试图理解我到目前为止的代码:
- (void)viewDidLoad
{
[super viewDidLoad];
[self loadURLWithString:@"https://myserver.com"];
}
+ (BOOL) isChallenge: (NSURLAuthenticationChallenge*) challenge validForConnection: (NSURLConnection*)conn{
SecTrustRef serverTrust=[[challenge protectionSpace] serverTrust];
//Some magic here?
// Check Server Certificate
SecTrustResultType evalResult;
if(SecTrustEvaluate(serverTrust,&evalResult) != errSecSuccess){
NSLog(@"Call to SecTrustEvaluate failed");
return NO;
}
if(evalResult != kSecTrustResultProceed){
NSLog(@"Server certificate invalid");
return NO;
}
NSLog(@"Server certificate valid");
return YES;
}
- (void)loadURLWithString: (NSString*)str{
NSURLConnection *conn =
[NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]] delegate:self];
[conn start];
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{
if([[self class] isChallenge:challenge validForConnection:connection])
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
else
[challenge.sender cancelAuthenticationChallenge:challenge];
}
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace{
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"Failed with error: %@",error);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(@"loading complete");
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
}
答案 0 :(得分:1)
不允许您尝试做的事情。有关详细信息,请参阅Apple开发人员论坛中的此主题: