setTaskDidReceiveAuthenticationChallengeBlock in AFNetworking 2.0
Asked Answered
S

2

2

Anybody know how to handle authentication in the 2.0 version of AFNetworking? I tried the below without success. The block is getting called (I had an NSLog in there) but the response is still a 401 error

[self setTaskDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing *credential) {
    *credential = [[NSURLCredential alloc] initWithUser:username password:password persistence:NSURLCredentialPersistenceForSession];
    return NSURLSessionAuthChallengeUseCredential;
}];
Summers answered 25/8, 2013 at 0:8 Comment(2)
Just curious, have you tried setting the credential property on your AFHTTPRequestOperation object?Collegiate
I'm subclassing AFHTTPClientSummers
C
4

I think this is a bug in AFNetworking 2.0. Here is the implementation:

- (void)URLSession:(NSURLSession *)session
              task:(NSURLSessionTask *)task
didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
 completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
{
    NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
    __block NSURLCredential *credential = nil;

    if (self.taskDidReceiveAuthenticationChallenge) {
        disposition = self.taskDidReceiveAuthenticationChallenge(session, task, challenge, &credential);
    } else {
        [self URLSession:session didReceiveChallenge:challenge completionHandler:completionHandler];
        return;
    }

    if (completionHandler) {
        completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, credential);
    }
}

Note that even though you're specifying NSURLSessionAuthChallengeUseCredential, AFNetworking is passing back NSURLSessionAuthChallengePerformDefaultHandling, which states "Default handling for the challenge - as if this delegate were not implemented; the credential parameter is ignored."

Collegiate answered 25/8, 2013 at 2:24 Comment(2)
I opened a pull request to resolve the issue. I don't have a server to check this against, but feel free to check out the code and let me know if it works now: github.com/AFNetworking/AFNetworking/pull/1252Collegiate
You're absolutely correct. I changed the source to pass in disposition to the completionHandler and now it's working perfectly. thank you so much!Summers
F
0

Swift 3.0

Override the method given,

override func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {

    completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))

}
Funda answered 12/1, 2017 at 16:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.