2010-02-24 63 views
2

我正在嘗試使用基本身份驗證來調用https Web服務(RESTful)。 它工作正常,如果我把憑據放在url本身,但我寧願將它添加到請求,以便密碼不會出現,例如在一個異常。iPhone:如何使用NSURLCredential獲取對HTTPS Web服務的基本身份驗證

我使用下面的代碼:

NSURLCredential *credential = [NSURLCredential credentialWithUser:@"myuser" 
                  password:@"mypassword" 
                  persistence:NSURLCredentialPersistenceForSession]; 

    NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc] 
              initWithHost:@"example.com" 
              port:443 
              protocol:@"https" 
              realm:nil 
              authenticationMethod:NSURLAuthenticationMethodHTTPBasic]; 


    [[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:credential 
                 forProtectionSpace:protectionSpace]; 

    NSURLConnection *theConnection = [NSURLConnection connectionWithRequest:theRequest delegate:self]; 

,但它不工作。代理方法被調用,我可以在那裏添加一個憑證,但理想情況下,我會將它與請求一起發送。

任何想法?

回答

2

如果是基本認證,請嘗試在標頭中發送憑證。每次都適合我。

在請求

NSString *authString = [[NSString stringWithFormat:@"%@:%@", userName, password] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
NSString *finalAuth = base64 of authString; 

在你請求的首部發送的用戶名和密碼,添加一個標頭字段名授權和價值"Basic " + finalAuth

+0

我以前試過,但無法讓它工作。我會再給它一次。 – Ian1971 2010-03-19 16:09:28

+0

它會給你一個錯誤?你確定錯誤是因爲驗證質詢失敗嗎? – lostInTransit 2010-03-20 04:49:23

+1

這對我有用,奇怪的是蘋果文檔中沒有提到它。此外,我不得不推出我自己的Base64編碼,這是非常可怕的。 – 2012-05-29 16:16:31

0

我錯過了最後一行代碼在哪裏使用NSURLConnection。確保您的代表正在迴應:

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace 

而且您的保護空間正在返回YES。

此外,請確保您的委託迴應:

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge 

在這裏,您可以在您的proposedCredential屬性創建到NSURLAuthenticationChallenge憑證,以及您NSURLProtectionSpace實例分配到的protectionSpace財產NSURLAuthenticationChallenge

+0

當它回到挑戰時它工作正常,但我試圖通過發送具有初始請求的憑證來避免這種往返行程。 – Ian1971 2010-03-19 16:08:09

+0

我不會認爲這是一次往返。無論哪種方式,連接都將受到挑戰,它將不得不提供憑證。 – benasher44 2010-03-20 01:04:11