AFNetworking setAuthenticationChallengeBlock

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

在浏览器提供的certifacete工作正常。

[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等工作正常。

知道我的错误在哪里?

我今晚遇到了类似的问题。 在进一步调查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