2013-08-06 35 views
0

我一直在試圖弄清楚如何在我的應用程序中創建登錄頁面。我有URL,有效的用戶名,密碼。我被告知使用基本身份驗證來執行此操作。基本身份驗證示例

到目前爲止,我實現了這個代碼

- (IBAction)loginClicked:(id)sender { 

    NSURL *url = [NSURL URLWithString:@"http://site-url.com"]; 

    NSString *loginString =(NSMutableString*)[NSString stringWithFormat:@"%@:%@",usernameTextField.text,passwordTextField.text]; 

    NSData *encodedLoginData=[loginString dataUsingEncoding:NSASCIIStringEncoding]; 

    NSString *authHeader=[NSString stringWithFormat:@"Basic %@", [encodedLoginData base64Encoding]]; 

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url 
              cachePolicy:NSURLRequestUseProtocolCachePolicy 
             timeoutInterval:3.0]; 

    [request setValue:authHeader forHTTPHeaderField:@"Authorization"]; 
    [request setHTTPMethod:@"POST"]; 

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
    [connection start]; 
} 

- (void) connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse *)response { 

    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; 

    // POW, here's the content of the webserver's response. 
    NSLog(@"Response -> %@",response); 

    int statusCode = [httpResponse statusCode]; 

    NSLog(@"response code:%d",statusCode); 
} 

- (void)connection:(NSURLConnection *)connection willReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { 
    if ([challenge previousFailureCount] == 0) { 
     NSLog(@"received authentication challenge"); 
     NSURLCredential *newCredential = [NSURLCredential credentialWithUser:usernameTextField.text 
                    password:passwordTextField.text 
                   persistence:NSURLCredentialPersistenceForSession]; 
     NSLog(@"credential created"); 
     [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge]; 
     NSLog(@"responded to authentication challenge"); 
    } 
    else { 
     NSLog(@"previous authentication failure"); 
    } 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 

    NSLog(@"Connection success."); 

} 

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
    NSLog(@"Connection failure."); 

,使其工作,但是當我用我的網站的網址,它只是給了我成功的消息和狀態代碼200,並且不調用委託方法 - willSendRequestForAuthenticationChallenge:

當我更改的URL gmail.com它給出以下輸出:

2013年8月6日12:06:08.674 CVReaderSGT [26544:A0B]接收到的認證挑戰 2013-08-06 12:06:08.674 CVReaderSGT [26544:a0b]密碼字符串:密碼 2013-08-06 12:06:07.67 CVReaderSGT [26544:a0b]用戶名字符串:admin 2013-08-06 12:06: 06:08.675 CVReaderSGT [26544:a0b]創建憑證 - >:管理員CVReaderSGT [26544:a0b]迴應認證挑戰CVReaderSGT [26544 :a0b]收到認證質詢 2013-08-06 12:06:09.026 CVReaderSGT [26544:a0b]用戶名字符串:admin 2013-08-06 12:06:09.026 CVReaderSGT [26544:a0b]密碼字符串:密碼 2013 -08-06 12:06:09.026 CVReaderSGT [26544:a0b]創建的憑證 - >:管理員 2013-08-06 12:06:09.026 CVReaderSGT [26544:a0b]對認證質詢 2013-08-06 12:06:10.069 CVReaderSGT [26544:a0b]收到驗證質詢 2013-08-06 12:06:10.069 CVReaderSGT [26544:a0b]用戶名字符串:admin 2013-08-06 12:06 :10.069 CVReaderSGT [26544:a0b]密碼字符串:密碼CVReaderSGT [26544:a0b]憑證已創建 - >:admin CVReaderSGT [26544:應答 - > {URL:https://accounts.google.com/ServiceLogin?service=mail&passive=true&rm=false&continue=https://mail.google.com/mail/&ss=1&scc=1&ltmpl=default&ltmplcache=2} {狀態代碼:200,頭部「Cache-Control」=「no-cache」響應於認證挑戰 2013-08-06 12:06:10.457 CVReaderSGT [26544:a0b] ,無店鋪「; 「Content-Type」=「text/html; charset = UTF-8」; Date =「Tue,2013年8月6日17:06:09 GMT」; Expires =「Mon,01-Jan-1990 00:00:00 GMT」; Pragma =「no-cache」; Server = GSE; 「Set-Cookie」=「GAPS = 1:LoAnsovSVriBDm6iP1r7zuYy7bTCpQ:3o2OJzkd7X87BrCH; Path = /; Expires = Thu,06-Aug-2015 17:06:09 GMT; Secure; HttpOnly,GALX = S0GMqJp_fyQ; Path = /; Secure」 ; 「Strict-Transport-Security」=「max-age = 2592000; includeSubDomains」; 「Transfer-Encoding」=身份; 「X-Auto-Login」=「realm = com.google & args = service%3Dmail%26continue%3Dhttps%253A%252F%252Fmail.google.com%252Fmail%252F」; 「X-Content-Type-Options」= nosniff; 「X-Frame-Options」= Deny; 「X-XSS-Protection」=「1; mode = block」; }} 2013-08-06 12:06:10.458 CVReaderSGT [26544:a0b]狀態碼 - > 200 2013-08-06 12:06:11.243 CVReaderSGT [26544:a0b]連接成功。

我不知道爲什麼我得到兩個不同的輸出,當我改變URL和爲什麼委託方法willSendRequestForAuthenticationChallenge:當我把我的URL沒有被調用。

Here's what the output looks like when using my URL: 
    2013-08-06 12:29:06.007 CVReaderSGT[26583:a0b] Response -> <NSHTTPURLResponse:  0x8e20ac0> { URL: http://XYZ.com/ } { status code: 403, headers { 
"Content-Length" = 1585; 
"Content-Type" = "text/html"; 
Date = "Tue, 06 Aug 2013 17:29:04 GMT"; 
MicrosoftSharePointTeamServices = "12.0.0.6219"; 
Server = "Microsoft-IIS/6.0"; 
"X-Powered-By" = "ASP.NET"; 
    } } 
    2013-08-06 12:29:06.007 CVReaderSGT[26583:a0b] Status code -> 403 
    2013-08-06 12:29:06.007 CVReaderSGT[26583:a0b] Connection success. 

我真的很想了解這個過程並使其工作。

任何人都可以請提供示例或提供正確的信息。謝謝。

+0

它們委託的方法'NSURLConnection'你實現? – ipinak

+0

@iPinak willReceiveAuthenticationChallenge: –

+0

當你把你的URL時,你是什麼意思?那個網址是什麼樣的?此外,正在努力完成的是什麼。從我在這裏看到的你嘗試驗證到Gmail,對吧?這顯然工作很好。 – ipinak

回答

1
// Authentication delegate methods 
- (BOOL)connection:(NSURLConnection *)connection 
canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace 
{ 
#pragma mark unused (connection) 
    assert(connection == connect); 
    assert(protectionSpace != nil); 

    BOOL retVal; 
    retVal = [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]; 

    return YES; 
} 

- (void)connection:(NSURLConnection *)connection 
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge 
{ 
    // Tries to connect 3 times, after the 3 attempts it cancels. 
    if ([challenge previousFailureCount] < 3) { 
     // Create credentials from the user name and password and save them, for this 
     // specific authentication challenge. 
     NSURLCredential *credentials = [NSURLCredential credentialWithUser:user password:pass persistence:NSURLCredentialPersistenceForSession]; 
//  [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; 
     // Handle the credentials according the state of the challenge. 
     if (challenge == nil) { 
      [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge]; 
     } 
     else { 
      [challenge.sender useCredential:credentials forAuthenticationChallenge:challenge]; 
     } 
    } 
    else { 
     [[challenge sender] cancelAuthenticationChallenge:challenge]; 
     NSLog(@"Wrong username or password"); 
    } 
} 

// Save credentials for further use. 
- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection 
{ 
    return YES; 
} 

看看這個。這對我有用。 嘗試在此處更改值以查看哪一個符合您的服務器要求。

retVal = [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];