NSURLSession didReceiveChallenge多个证书

时间:2016-11-26 14:31:43

标签: ios objective-c ssl nsurlsession

如何根据服务器指定多个证书? 在session:didReceiveChallenge方法中,我可以返回NSURLCredential,但我没有找到确定挑战来自哪个网址的方法。

我想做这样的事情:

-(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
{

  // get the certificate depending on the url
  NSString *certificatePath;
  if ([url isEqualToString: @"server1.com"]) {
      certificatePath = [[[NSBundle mainBundle] bundlePath] stringByAppendingString:@"/server1.p12"];
  } else if ([url isEqualToString: @"server2.com"]) {
      certificatePath = [[[NSBundle mainBundle] bundlePath] stringByAppendingString:@"/server2.p12"];
  }

  //... some certificate stuff

  NSURLCredential *credential = [NSURLCredential credentialWithIdentity:myIdentity certificates:(__bridge NSArray*)certsArray persistence:NSURLCredentialPersistencePermanent];
  completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
}

1 个答案:

答案 0 :(得分:1)

我终于找到了答案,你可以得到NSURLAuthenticationChallenge的主持人:

NSString* host = challenge.protectionSpace.host;

就是这样