NSURLConnection 的委托方法,请求身份验证挑战没有被触发?



我使用NSURLConnection调用Web服务,并且在我的密钥链中存在一个客户端证书,我将其设置为- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge 中的凭据

在我删除此证书并将新证书添加到密钥链后,NSURLConnection仍然保留我已经提供的凭据,并在我删除旧证书之前返回417状态错误代码,即200。

有没有办法让NSURLConnection强制要求凭据。?或者如何关闭现有SSL连接或身份验证质询的凭据。

NSURLConnection是一个善变的野兽,过去几天我也遇到过类似的问题。但我已经找到了解决我的问题的方法,并提出了一些建议,说明你遇到这种问题的原因。

TLS

首先,发生在您身上的事情可能是TLS层缓存凭据。这是由于建立TLS连接在计算上是昂贵的[1]。

可能的解决方案是更改您正在使用的DNS名称,例如在字符串末尾添加一个句点(.),因为DNS协议接受以句点结尾的字符串作为完全限定的DNS名称。我还看到有人在所有URL请求中添加了一个标签(#),从而诱使系统从不查找存储的凭据,而只是启动didRecieveAuthenticationChallenge调用[2]。

Cookie

另一种可能性是,服务器正在设置一个需要清除的cookie。您可以通过以下操作来做到这一点:

-(void)clearCookies:(NSString *)urlString{
    NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedCookieStorage];
    NSURL *url = [[NSURL alloc] initWithString urlString];
    NSArray *cookies = [cookieStorage cookiesForURL:tempURL];
    for(NSHTTPCookie *cookie in cookies){
        //iterate over all cookies and delete them
        [cookieStorage deleteCookie:cookie];
    }
}

NSURL基本存储

现在,凭证可能仍存储在sharedCredentialStorage中,因此应通过以下操作擦除:

NSURLCredentialStorage *store = [NSURLCredentialStorage sharedCredentialStorage];
if(store !=nil){
   for(NSURLProtectionSpace *protectionSpace in [store allCredentials]){
      NSDictionary *map = [[NSURLCredentialStorage sharedCredentialStorage] 
                                  credentialsForProtectionSpace:protectionSpace];
      if(map!=nil){
         for(NSString *user in map){
             NSURLCredential *cred = [map objectForKey:user];
             [store removeCredential:cred forProtectionSpace:protectionSpace];
          }
      }
   }
}

我希望这些会有所帮助。

最新更新