3

我有一个 iOS 应用程序,它登录用户,然后使用appKey. didReceiveAuthenticationChallenge委托方法 on足以提供NSURLConnection带有NSURLCredential. 但是,我在创建一个NSURLCredential只有一个appKey(只有一个身份验证数据,而不是两个)时遇到了麻烦。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委托方法中获取错误信息(我知道didReceiveResponse)?

4

1 回答 1

2

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

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

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

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"
于 2013-08-18T21:37:30.967 回答