首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >基本Auth示例

问基本Auth示例
EN

Stack Overflow用户
提问于 2013-08-06 17:12:29
回答 1查看 871关注 0票数 0

我一直在努力想办法在我的应用程序中创建一个登录页面。我有URL,有效用户名,密码。有人告诉我用基本的方法来做这件事。

到目前为止,我实现了以下代码

代码语言:javascript
复制
- (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 CVReaderSGT26544 26544:a0b收到认证挑战2013-08-06 12:06:08.674 CVReaderSGT26544 26544:a0b用户名字符串: admin 2013-08-06 12:06:08.674 CVReaderSGT26544 26544:a 0b密码字符串:密码2013-08-06 12:06:08.675 CVReaderSGT26544 26544:08.675 CVReaderSGT26544 26544:admin 2013-08-06 12:06:08.675 CVReaderSGT26544 26544:A0b响应认证挑战2013-08-06 12:06:06:09.025 received 26544:a0b收到身份验证挑战2013-08-06 12:06:09.026 CVReaderSGT26544 26544:a0b用户名字符串: admin 2013-08-06 12:06:09.026 CVReaderSGT26544 26544:密码串:密码2013-08-06 12:06:09.026 CVReaderSGT26544 26544:A0b凭据创建->:admin 2013-08-06 12:06:09.026 CVReaderSGT26544 26544:A0b响应认证挑战2013-08-06 12:06:10.069 CVReaderSGT26544 26544:a0b收到认证挑战2013-08-06 12:06:06:10.069 received 26544:a0b用户名:2013-08-06 12:06:10.069 CVReaderSGT26544 26544:a0b密码字符串:密码2013-08-06 12:06:10.069 CVReaderSGT26544 26544:a0b凭据创建->:admin 2013-08-06 12:06:10.070 CVReaderSGT26544 26544:a0b响应认证挑战2013-08-06 12:06:10.457 CVReaderSGT26544 26544:a0b响应->{ mplcache=2 }{mplcache=2}{状态代码: 200,标题{“缓存-控制”=“无缓存,无存储”;"Content-Type“= "text/html;charset=UTF-8";Date = "Tue,2013年8月6日17: 06 :09 GMT";Expires = "Mon,01-1990年1月-1990 00:00 GMT";Pragma = "no-cache";Server = GSE;"Set-Cookie”= "GAPS=1:LoAnsovSVriBDm6iP1r7zuYy7bTCpQ:3o2OJzkd7X87BrCH;Path=/;Expires=Thu,06-2015 17:06:09 GMT;Secure;HttpOnly,GALX=S0GMqJp_fyQ;Path=/;Secure;“严格-传输-安全”=“最大年龄=2592000;includeSubDomains";”传输-编码“=标识;”X-自动登录“=”X-内容-类型-选项“= nosniff;”X-帧-选项“=拒绝;”XSS保护“= "1;mode=block";}2013年-08-06 12:06:10.458 CVReaderSGT26544 26544:a0b状态代码-> 200 2013-08-06 12:06:11.243 CVReaderSGT26544 26544:a0b连接成功。

当我更改URL时,我不知道为什么要得到两个不同的输出,以及为什么当我放置URL时没有调用委托方法willSendRequestForAuthenticationChallenge:。

代码语言:javascript
复制
  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.

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

请任何人提供例子或提供正确的信息。谢谢。

EN

回答 1

Stack Overflow用户

发布于 2013-08-06 17:20:05

代码语言:javascript
复制
// 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];

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18086408

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档