1

我是 iOS 和 https 的新手。我是一名初学软件的学生。我想编写一个应用程序,从我的 uni 帐户中提取数据(例如班级编号、公告等)并在我的应用程序上显示。

通常,我会去我的大学学生页面,用我的用户名和密码登录,这些信息就会显示在浏览器上。

我试过使用 NSURLConnection 及其委托。请看下面我的代码。一开始,在connection:didReceviveAuthenticationChallenge方法中,我通过[NSURLCredential withUser:password:persistence]创建了一个NSURLCredential对象。它不起作用。然后我尝试做NSLog,然后我发现protectionSpace.authenticationMethod是NSURLAuthenticationMethodServerTrust。

然后,我尝试阅读 Apple 的文档和一些谷歌资源。但是,我无法真正理解它,然后我编辑了我的代码,如下所示(这是我的最终版本,它仍然无法正常工作)。

我不太明白的一点是:我希望服务器应该询问我的用户名和密码。取而代之的是,它要求 credentialForTrust,它基于我读过的那些文档,他们建议我评估 NSURLConnection 委托对服务器的信任。但是,服务器从未询问用户名和密码。那么,服务器如何知道我正在访问哪个帐户。

所以,我认为这应该是证书(信任)与用户名和密码之间的某种关系。我真的不明白这些东西是如何工作的。

我想,我的问题可能不是很清楚或其他什么,而且可能很愚蠢。我接受这一点,因为我从来没有学过所有这些东西。

所以,请有人向我解释这些事情是如何工作的。您可以假设我对什么是 https、SSL、NSURLConnection、NSURLCredential 等有一些基本的了解,请指导我找到解决方案。

我很感激你的所有努力。

下面是我的代码,(它不工作)。

连接中的 NSLog():didReceiveAuthenticationChallenge,打印出“NSURLAuthenticationMethodServerTrust”

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
    return YES;
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    NSLog(@"authenticationMethod is:  %@\n",challenge.protectionSpace.authenticationMethod);
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]){
          [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
    }else{
            NSURLCredential *creden = [[NSURLCredential alloc] initWithUser:myusername password:mypassword persistence:NSURLCredentialPersistenceForSession];
            [[challenge sender] useCredential:creden forAuthenticationChallenge:challenge];
    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"didFailWithError:  %@\n  %@\n",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
     [self.myData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [self.myData setLength:0];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
     NSString *str = [[NSString alloc] initWithData:self.myData    encoding:NSASCIIStringEncoding];
    NSLog(@"Data in String %@", str);
}
4

1 回答 1

1

NSURLAuthenticationMethodServerTrust当 URL 加载系统不信任服务器时,就会出现挑战。如果您想避免这些调用,请确保 iOS 信任您服务器的证书(通过手动安装它,或者让像 Verisign 这样的受信任的根对其进行签名)。

于 2013-07-10T17:53:22.580 回答