NSURLConnection – 禁用身份validation质询响应机制

情况

  • 使用AFNetworking(NSURLConnection)来访问我的服务器API
  • API需要使用令牌作为用户名的基本身份validation
  • 当令牌无效时,API返回HTTP 401
  • 我在任何请求之前设置基本身份validation标头
  • 如果它返回401,我重试像这样:

    AFHTTPRequestOperation *requestOperation = [MyHTTPClient.sharedClient HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) { processSuccessBlock(operation, responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { processFailureBlock(operation, error); if (operation.response.statusCode == 401) [MyHTTPClient.sharedClient refreshTokenAndRetryOperation:operation success:processSuccessBlock failure:processFailureBlock]; }]; 

问题

  • 当服务器返回具有基本authentication质询的HTTP 401时,AFNetworking / NSURLConnection 将两次发送相同的请求 (初始请求,然后应答authentication质询)
  • 但由于上面的代码我自己处理HTTP 401, 这是完全没有必要的 ,我希望它停止自动应答authentication的挑战

我试过了什么

  • 响应cancelAuthenticationChallenge:将发送cancelAuthenticationChallenge:正在中止第二个调用,但它给出错误代码-1012(NSURLErrorUserCancelledAuthentication),而不是401,并掩盖真正的响应

如何禁用身份validation质询响应机制,以便在不调用服务器响应的情况下获得服务器响应两次?

您有几个选项来完全自定义身份validation处理:

  1. 使用setWillSendRequestForAuthenticationChallengeBlock:setAuthenticationAgainstProtectionSpaceBlock:AFURLConnectionOperation类中设置相应的块,您可以在其中调整所需的机制。

    标题包含文档。

  2. 覆盖connection:willSendRequestForAuthenticationChallenge:AFURLConnectionOperation的子类中。 这将有效地覆盖AFNetworking中的完整身份validation机制设置。

请注意,您不能禁用“服务器validation客户端身份”身份validation质询 – 这是服务器的一部分。 您必须为请求的身份validation方法提供正确的凭据。

尝试这个。

 - (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { SecTrustRef trust = challenge.protectionSpace.serverTrust; NSURLCredential *cred; cred = [NSURLCredential credentialForTrust:trust]; [challenge.sender useCredential:cred forAuthenticationChallenge:challenge]; }