2010-06-01 20 views
8

大家上午,NSURLConnection的,的NSURLRequest,不可信的證書和用戶身份驗證

我一直在嘗試寫做一些需要驗證遠程Web服務獲取的應用程序。我的主要問題是大多數這些遠程服務器(並且有很多)沒有有效的證書。我有code to accept the invalid certificate和代碼來回應正確的uname &通過挑戰(下)。我遇到的問題是讓兩人一起玩。我似乎無法找到一種方法來發送挑戰NSURLCredential或一種正確鏈接回調的方法。當我嘗試鏈接他們時,我無法將我的NSURLRequest撥打電話didReceiveAuthenticationChallenge兩次。

任何想法,將不勝感激!

規範認證...

-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge 
{ 
    if(!hasCanceled){ 
     if ([challenge previousFailureCount] == 0) { 
      NSURLCredential *newCredential; 
      newCredential=[NSURLCredential credentialWithUser:_username password:_password persistence:NSURLCredentialPersistenceNone]; 
      [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge]; 
     } 
     else { 
      [[challenge sender] cancelAuthenticationChallenge:challenge]; 
      NSLog(@"Bad Username Or Password"); 
      badUsernameAndPassword = YES; 
      finished = YES; 
     } 
    } 
} 

回答

9

你可以只回復到NSURLAuthenticationChallenge與這一挑戰的憑證。您可以確定使用哪種類型的挑戰:

[[challenge protectionSpace] authenticationMethod] 

可能的值是documented here。在服務器證書無效的情況下,驗證方法將爲NSURLAuthenticationMethodServerTrust。在您的代碼中,您應該檢查身份驗證方法並進行適當的響應。

if ([challenge previousFailureCount] > 0) { 
    // handle bad credentials here 
    [[challenge sender] cancelAuthenticationChallenge:challenge]; 
    return; 
} 

if ([[challenge protectionSpace] authenticationMethod] == NSURLAuthenticationMethodServerTrust) { 
    // check if the user has previously accepted the certificate, otherwise prompt 
} else if ([[challenge protectionSpace] authenticationMethod] == /* your supported authentication method here */) { 
    [[challenge sender] useCredential:/* your user's credential */ forAuthenticationChallenge:challenge]; 
} 

如果您每次都沒有同時遇到身份驗證問題,這並非錯誤。您可以在創建憑據時緩存憑據。如果你這樣做,你不一定會被提示。

+0

工作就像一個魅力。需要正確實施「canAuthenticateAgainstProtectionSpace」方法來讓我的應用程序調用此方法。但之後一切都很好。謝謝! – Staros 2010-06-03 20:44:51

相關問題