基本Auth示例

时间:2013-08-06 17:12:30

标签: ios basic-authentication

我一直想弄清楚如何在我的应用中制作登录页面。我有URL,有效的用户名,密码。有人告诉我使用基本的auth来做。

到目前为止,我实现了这段代码

- (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.");

使其工作,但当我使用我的网站URL时,它只给我成功消息和状态代码200并且不调用委托方法 - willSendRequestForAuthenticationChallenge:

当我将URL更改为gmail.com时,它提供以下输出:

  

2013-08-06 12:06:08.674 CVReaderSGT [26544:a0b]收到身份验证质询   2013-08-06 12:06:08.674 CVReaderSGT [26544:a0b]用户名字符串:admin   2013-08-06 12:06:08.674 CVReaderSGT [26544:a0b]密码字符串:密码   2013-08-06 12:06:08.675创建CVReaderSGT [26544:a0b]凭证 - > :管理员   2013-08-06 12:06:08.675 CVReaderSGT [26544:a0b]回复了身份验证质询   2013-08-06 12:06:09.025 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]密码字符串:密码   2013-08-06 12:06:10.069创建CVReaderSGT [26544:a0b]凭证 - > :管理员   2013-08-06 12:06:10.070 CVReaderSGT [26544:a0b]回复了身份验证质询   2013-08-06 12:06:10.457 CVReaderSGT [26544:a0b]响应 - > {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,headers {       “Cache-Control”=“no-cache,no-store”;       “Content-Type”=“text / html; charset = UTF-8”;       日期=“星期二,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”;       “转移编码”=身份;       “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”=拒绝;       “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.

我真的想了解这个过程并让它发挥作用。

任何人都可以提供示例或提供正确的信息。感谢。

1 个答案:

答案 0 :(得分: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];