ios - NSURLCredential 认证只有一把 key

标签 ios objective-c curl nsurlconnection nsurlcredential

我有一个 iOS 应用程序,它可以让用户登录,然后使用 appKey 对该用户进行身份验证。 NSURLConnection 上的 didReceiveAuthenticationChallenge 委托(delegate)方法足以提供带有 NSURLCredential 的用户名/密码。但是,我在创建只有一个 appKeyNSURLCredential 时遇到了问题(只是一个授权数据,而不是两个)。无论如何,只有一个 key 才能使用 NSURLConnection 向服务器提供身份验证详细信息吗?

以下 curl 请求仅提供 appKey 即可完美运行,无需提供密码:

curl -u <app key>: -H "Accept: application/json" https://dev.sitename.com/api/v1/webpage -v

这就是我将上述 cURL 身份验证部分转换为 Objective-C 的方式:

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    // Authenticate the user with AppKey based on the credentials provided
    if ([challenge previousFailureCount] == 0) {
        NSURLCredential *credential = [NSURLCredential credentialWithUser:[keychainItem objectForKey:@"APP KEY"] password:nil persistence:NSURLCredentialPersistenceForSession];
        [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
    }
}

这应该可行,但每次我尝试时,身份验证都会失败。如您所见,我已将 password 参数设置为 nil。我也尝试填写这两个参数。似乎没有任何效果。

关于如何使用 NSURLConnection 只能将一个参数传递给服务器有什么想法吗?有什么方法可以从 didReceiveAuthenticationChallenge 委托(delegate)方法中获取错误信息(我知道 didReceiveResponse)?

最佳答案

这似乎是 NSURLCredential 的未记录行为:当将 nil 作为密码传递给 credentialWithUser:password:persistence: 时,并使用此凭据来响应身份验证质询,iOS 完全忽略该凭据。

解决方案是当您不想使用密码时,将nil替换为空的NSString (@"") .

所以你的代码应该是这样的:

NSURLCredential *credential = [NSURLCredential credentialWithUser:[keychainItem objectForKey:@"APP KEY"] password:@"" persistence:NSURLCredentialPersistenceForSession];

这是我使用 nil 密码从我的 nginx 日志中得到的:

xxx.xxx.xxx.xxx - - [18/Aug/2013:23:21:14 +0200] "GET /tmp HTTP/1.1" 401 188 "-" "test/1.0 CFNetwork/609.1.4 Darwin/12.4.0"

使用空字符串(apikey 是用于响应挑战的用户名):

xxx.xxx.xxx.xxx - apikey [18/Aug/2013:23:21:16 +0200] "GET /tmp HTTP/1.1" 200 136 "-" "test/1.0 CFNetwork/609.1.4 Darwin/12.4.0"

关于ios - NSURLCredential 认证只有一把 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18303111/

相关文章:

ios - NSMutableArray 到 UITableView

ios - - (void)chatDidReceiveMessage :(QBChatMessage *)message not working

ios - 使用 XIB 的自定义 NSView/UIView 子类?

php - 从一个虚拟机实例到另一台虚拟机 (Vagrant) 的 Curl 请求似乎不起作用

ios - Mapkit: mkannotation - 如何正确重用?

ios - 什么时候释放保留对象(分配给弱变量对象)

iphone - 从服务器加载 "weird characters"的标签

ios - 在没有 pod 的情况下导入 AFNetworking

PHP CURL 似乎忽略了 cookie jar/文件

hadoop - 使用Knox Gateway-0.3.0将数据加载到hadoop集群时,http 045:方法不允许错误