当使用客户端证书身份validation时,为什么我一直得到NSURLErrorDomain代码= -1206?

以下代码是我使用以前发布的关于ios客户端证书身份validation的代码。 每个人都说这是有效的,但是为什么它对我有用呢?!?!

我不断收到以下错误:

connection didFailWithError: Error Domain=NSURLErrorDomain Code=-1206 "The server “www.mywebsite.com” requires a client certificate. 

我已经至less跟着4个post关于这个相同的主题,在其他类似的网站stackoverflow和2。 他们都说同样的事情,除非它不工作。

我知道我的PKCS12文件的工作原理,因为我通过电子邮件将其发送到我的ipad,我在ipad keychain上安装了它,并且我能够使用Safari访问和授权证书标识。 只是当我试图在第三方应用程序中使用NSURLConnection时,它拒绝让我这样做。

任何build议,欢迎,我觉得我已经用尽了我的select。


  // Download PKCS12 Cert from my FTP server. NSString *stringURL = @"ftp://user:password@myipaddress/myclientId.p12"; NSString* webStringURL = [stringURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString:webStringURL]; NSData *p12Data = [NSData dataWithContentsOfURL:url]; if ( p12Data ) { CFDataRef inP12data = (__bridge CFDataRef)p12Data; SecIdentityRef myIdentity; SecTrustRef myTrust; OSStatus errMsg = NULL; // This is the same function that has been reposted in all the other posts about ios client certification authentication. So i'm not going to repost that. errMsg = extractIdentityAndTrust(inP12data, &myIdentity, &myTrust); SecCertificateRef myCertificate; SecIdentityCopyCertificate(myIdentity, &myCertificate); const void *certs[] = { myCertificate }; CFArrayRef certsArray = CFArrayCreate(NULL, certs, 1, NULL); NSURLCredential *credential = [NSURLCredential credentialWithIdentity:myIdentity certificates:(__bridge NSArray*)certsArray persistence:NSURLCredentialPersistenceNone]; [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; 

错误是在这一行。 第二个参数需要设置为“无”

  NSURLCredential *credential = [NSURLCredential credentialWithIdentity:myIdentity certificates:(__bridge NSArray*)certsArray persistence:NSURLCredentialPersistenceNone]; 

变成:

  NSURLCredential *credential = [NSURLCredential credentialWithIdentity:myIdentity certificates:nil persistence:NSURLCredentialPersistenceNone]; 

机会是你的.p12包含中间证书和您的服务器需要那些中级证书。

您可以使用wiresharkvalidation您的代码将以身份的重复证书发送,但在客户端证书响应中没有中间证书。

如果出现这种情况,您还需要从p12中提取证书并通过创buildNSURLCredentials:

 int count = SecTrustGetCertificateCount(myTrust); NSMutableArray* myCertificates = nil; if (count > 1) { myCertificates = [NSMutableArray arrayWithCapacity:SecTrustGetCertificateCount(myTrust)]; for (int i = 1; i < count; ++i) { // remove the leaf cert [certs addObject:(id)SecTrustGetCertificateAtIndex(myTrust, i)]; } } NSURLCredential *credential = [NSURLCredential credentialWithIdentity:myIdentity certificates:myCertificates persistence:NSURLCredentialPersistenceNone]; 

而且,将nil传递给NSURLCredential不应该破坏任何代码。 请参阅Apple的示例: https : //developer.apple.com/library/ios/documentation/Security/Conceptual/CertKeyTrustProgGuide/iPhone_Tasks/iPhone_Tasks.html 。 但是将空数组@ @ []传递给NSURLCredential将会崩溃。