AFNetworking setAuthenticationChallengeBlock

雨燕双飞 提交于 2019-12-06 02:36:35

问题


My server requires a client certifiacte, after some time searching and reading examples in AFNetworking docs I tried to set setAuthenticationChallengeBlock and provide a client certificate.

In browser provided certifacete works fine.

[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];

but the code inside block is never being called and server returns 403 error as expected.

The code in other blocks such as setUploadBlock etc. works fine.

Any idea where is my mistake?


回答1:


I ran into a similar issue tonight. After further investigation of the AFNetworking header files I found my issue. I was forgetting to set the setAuthenticationAgainstProtectionSpaceBlock block on my operation.

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

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

        return YES;

    }];

I believe AFNetworking uses this block to handle the NSURLConnectionDelegate Protocol method: - (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace.



来源:https://stackoverflow.com/questions/16137220/afnetworking-setauthenticationchallengeblock

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!