【问题标题】:Intermittent SSL error in iOS for NSURLConnectionNSURLConnection 在 iOS 中出现间歇性 SSL 错误
【发布时间】:2016-05-06 18:26:04
【问题描述】:

我正在使用不再是有效 SSL 证书的自定义 SSL 连接到服务器。我更新了我的 info.plist 以允许任意和添加的代码绕过 NSURLConnection 委托的挑战。

-(void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
NSLog(@"willSendRequestForAuthenticationChallenge");
BOOL trusted = NO;
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
    NSString *thePath = [[NSBundle mainBundle] pathForResource:@"cert" ofType:@"der"];
    NSData *certData = [[NSData alloc] initWithContentsOfFile:thePath];
    CFDataRef certDataRef = (__bridge_retained CFDataRef)certData;
    SecCertificateRef cert = SecCertificateCreateWithData(NULL, certDataRef);
    SecPolicyRef policyRef = SecPolicyCreateBasicX509();
    SecCertificateRef certArray[1] = { cert };
    CFArrayRef certArrayRef = CFArrayCreate(NULL, (void *)certArray, 1, NULL);
    SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
    SecTrustSetAnchorCertificates(serverTrust, certArrayRef);
    SecTrustResultType trustResult;
    SecTrustEvaluate(serverTrust, &trustResult);
    trusted = (trustResult == kSecTrustResultUnspecified);
    CFRelease(certArrayRef);
    CFRelease(policyRef);
    CFRelease(cert);
    CFRelease(certDataRef);
}
if (trusted) {
    [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
} else {
    [challenge.sender performDefaultHandlingForAuthenticationChallenge:challenge];
}
}

但是,间歇性地发生 SSL 错误。它没有调用代理willSendRequestForAuthenticationChallenge,而是直接调用didFailWithError 代理。

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

【问题讨论】:

    标签: ios objective-c ssl nsurlconnection


    【解决方案1】:

    您的代码有细微的错误。如果结果状态是以下任一情况,则证书是受信任的:

    • kSecTrustResultUnspecified
    • kSecTrustResultProceed

    此外,对于过期的证书,上面的代码应该会看到 kSecTrustResultRecoverableTrustFailure 错误,除非您调用:

    SecTrustSetOptions(serverTrust,kSecTrustOptionAllowExpired);
    

    但是,强烈建议不要允许过期的证书。

    除非“不再有效”,否则您的意思是它违反了 iOS 9 的最低要求,在这种情况下是的,如果针对 iOS 9 SDK 编译,您将获得在 iOS 9 上运行时所描述的行为.有关详细信息,请在 Google 上搜索 App Transport Security。

    【讨论】:

      猜你喜欢
      • 2016-05-20
      • 2012-08-11
      • 1970-01-01
      • 2015-04-02
      • 1970-01-01
      • 2023-03-11
      • 2013-05-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多