SetTaskDidReceiveAuthenticationChallengeBlock in AFNetworking 2.0

Does anyone know how to handle authentication in version 2.0 of AFNetworking? I tried this without success. The block receives the call (I had an NSLog there), but the answer is still error 401

[self setTaskDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing *credential) { *credential = [[NSURLCredential alloc] initWithUser:username password:password persistence:NSURLCredentialPersistenceForSession]; return NSURLSessionAuthChallengeUseCredential; }]; 
+1
source share
2 answers

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 if you specify NSURLSessionAuthChallengeUseCredential , AFNetworking passes back NSURLSessionAuthChallengePerformDefaultHandling , which says: "The default processing for the call is as if this delegate was not implemented, the credential parameter is ignored."

+4
source

Swift 3.0

Cancel the proposed method,

 override func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!)) } 
0
source

Source: https://habr.com/ru/post/976023/


All Articles