仅使用一个密钥进行NSURLCredential身份验证

时间:2013-08-18 19:57:43

标签: ios objective-c curl nsurlconnection nsurlcredential

我有一个iOS应用程序,用于登录用户,然后使用appKey对该用户进行身份验证。 didReceiveAuthenticationChallenge上的NSURLConnection委托方法足以提供NSURLCredential的用户名/密码。但是,我在创建只有NSURLCredential的{​​{1}}时遇到问题(只有一个身份验证数据,而不是两个)。无论如何都要向只有密钥的appKey的服务器提供身份验证详细信息?

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

appKey

这就是我将上述curl -u <app key>: -H "Accept: application/json" https://dev.sitename.com/api/v1/webpage -v 身份验证部分转换为Objective-C的方式:

cURL

这应该可行,但每次尝试时都会失败。如您所见,我已将- (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)?

1 个答案:

答案 0 :(得分:2)

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

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

因此,您的代码应该类似于:

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

这是我从我的nginx日志中获得的nil密码:

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"