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

为了使它工作,但是当我使用我的站点 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] 用户名字符串:管理员 2013-08-06 12:06:09.026 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: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] 密码字符串:password 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<mpl=default<mplcache=2} {状态码:200,标头{“缓存控制”=“无缓存,无存储”;“内容类型”=“文本/html;字符集=UTF-8”;日期 =“格林威治标准时间 2013 年 8 月 6 日星期二 17:06:09”;过期 =“星期一,1990 年 1 月 1 日 00:00:00 GMT”;Pragma = "无缓存"; 服务器 = 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-自动登录" = "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 时会得到两个不同的输出,以及为什么在我放置我的 URL 时没有调用委托方法 willSendRequestForAuthenticationChallenge:。

  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.

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

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

4

1 回答 1

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];

于 2013-08-06T17:20:05.890 回答