在NSURLCredential initWithTrust方面需要帮助:

时间:2011-07-04 08:37:48

标签: cocoa nsurlconnection nsurlcredential

在过去的几个小时里,我一直在靠墙碰头,在任何地方都找不到任何解决方案。 我正在开发一个应用程序,以了解如何使用JSON,所以我只是构建一个简单的应用程序,首先只返回我在GitHub上的所有回购列表。 我能够从NSURLConnection返回的数据中提取JSON响应没有问题,不幸的是,当我尝试访问需要身份验证的任何内容时,响应总是{ message = "Not Found"; } 如果我发送请求只是获取有关我的用户名的公开信息,我会收到正确的回复,并提供所有正确的信息,因此我知道我已成功与api.github.com进行通信。 首先启动我使用的请求:

    -(IBAction)retriveRepos:(id)sender
{
    responseData = [[NSMutableData data] retain];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"https://api.github.com/user/repos"]];
    [request setHTTPMethod:@"GET"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge被调用时,身份验证方法会以NSURLAuthenticationMethodServerTrust的形式返回(我觉得这很奇怪,因为我觉得我应该提供用户名和密码来登录)。根据Apple的文档,我需要使用NSURLCredential创建initWithTrust:。我用Google搜索了答案,最后发现了一些地方,只是从传递的serverTrust的{​​{1}}中取出protectionSpace。这样做没有显示任何影响的迹象事实上,看起来我的NSURLAuthenticationChallenge几乎没有任何内容。

NSURLCredential

我使用了更广泛的日志记录,表明事实上if ([[challenge protectionSpace] authenticationMethod] == NSURLAuthenticationMethodServerTrust) { NSLog(@"challenge.protectionSpace.serverTrust: %@", challenge.protectionSpace.serverTrust); // This logs "challenge.protectionSpace.serverTrust: <SecTrust 0x10340b2e0 [0x7fff7cc12ea0]>" NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:challenge.protectionSpace.serverTrust]; NSLog(@"credential: %@", credential); // Always logs something like "credential: <NSURLCredential: 0x1002d2f20>: (null)" NSURLCredential *otherCredential = [[NSURLCredential alloc] initWithUser:@"user" password:@"password" persistence:NSURLCredentialPersistencePermanent]; NSLog(@"otherCredential: %@", otherCredential); // This logs otherCredential: <NSURLCredential: 0x1018d0840>: user" [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; } 确实存在(起初我以为它根本没有创建),但它没有设置credential的属性。我只能假设问题出在我的身份验证中,但我按照我在信中找到的示例进行了操作。我正在使用Lion的GM预览版,所以我猜我可能发现了一个错误,或者GitHub API中存在一些错误,但考虑到我的技能水平,我发现我很可能是一个正在寻找的白痴坐在我面前的答案。 如果有人知道一个好的指南,它实际上会引导您完成身份验证的所有步骤(最好是所有样式),而不是严格缺乏的Apple URL加载指南,它只是说使用方法但没有说明{{1来自它会非常感激。

1 个答案:

答案 0 :(得分:0)

NSURLAuthenticationMethodServerTrust是您在协商SSL连接时会得到的。它让您有机会评估服务器的信任(反之亦然)。 Technote 2232详细描述了这一点。您的代表需要处理它,技术说明链接到示例代码高级URL连接的源代码,它应该向您展示如何响应该挑战。

请不要绝望,如果您的服务器有来自HTTP身份验证的步骤,您会看到代理人稍后会这样做。