6

我的服务器需要客户端证书,经过一段时间搜索和阅读 AFNetworking 文档中的示例后,我尝试设置 setAuthenticationChallengeBlock 并提供客户端证书。

在浏览器中提供的证书工作正常。

[requestOperation setAuthenticationChallengeBlock:^(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge)
    {
        NSLog(@"AuthenticationChallenge");

        NSString *thePath = [[NSBundle mainBundle] pathForResource:@"client" ofType:@"pfx"];
        NSData *PKCS12Data = [[NSData alloc] initWithContentsOfFile:thePath];
        CFDataRef inPKCS12Data = (__bridge CFDataRef)PKCS12Data;
        SecIdentityRef identity;

        [self extractIdentity:inPKCS12Data :&identity];

        SecCertificateRef certificate = NULL;
        SecIdentityCopyCertificate (identity, &certificate);

        const void *certs[] = {certificate};
        CFArrayRef certArray = CFArrayCreate(kCFAllocatorDefault, certs, 1, NULL);

        NSURLCredential *credential = [NSURLCredential credentialWithIdentity:identity certificates:(__bridge NSArray*)certArray persistence:NSURLCredentialPersistencePermanent];
        [challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
    }];
    [requestOperation start];

但是块内的代码永远不会被调用,并且服务器按预期返回 403 错误。

其他块中的代码,例如 setUploadBlock 等。工作正常。

知道我的错误在哪里吗?

4

1 回答 1

4

今晚我遇到了类似的问题。在进一步调查 AFNetworking 头文件后,我发现了我的问题。我忘记setAuthenticationAgainstProtectionSpaceBlock在我的操作中设置障碍。

    [requestOperation  setAuthenticationAgainstProtectionSpaceBlock:^BOOL(NSURLConnection *connection, NSURLProtectionSpace *protectionSpace) {

        NSLog(@"Auth against protected space [%@]", protectionSpace);

        return YES;

    }];

我相信 AFNetworking 使用这个块来处理 NSURLConnectionDelegate 协议方法:- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace

于 2013-05-02T03:03:29.037 回答