我有一个iOS应用程序,它登录一个用户,然后用一个appKey对该用户进行身份验证。didReceiveAuthenticationChallenge委托方法在NSURLConnection上足以提供带有NSURLCredential的用户名/密码。但是,我很难用一个NSURLCredential创建一个appKey (只是一个auth数据,而不是两个)。是否有任何方式向只有密钥的NSURLConnection服务器提供身份验证详细信息?
以下curl请求通过只提供appKey,而不提供密码,工作得很好:
curl -u <app key>: -H "Accept: application/json" https://dev.sitename.com/api/v1/webpage -v以下是我如何将上述cURL身份验证部分转换为目标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)获取错误信息吗?
发布于 2013-08-18 21:37:30
这似乎是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"https://stackoverflow.com/questions/18303111
复制相似问题