![](/img/trans.png)
[英]How to remove NSURLCredential storage for https authentication in iOS
[英]NSURLCredential Authentication with only one key
我有一个iOS应用程序登录用户,然后使用appKey
对该用户进行身份验证。 在didReceiveAuthenticationChallenge
上委托方法NSURLConnection
是足以提供用户名/密码与NSURLCredential
。 但是,我在创建仅使用appKey
的NSURLCredential
时遇到了麻烦(只有一个auth数据,而不是两个)。 无论如何,只使用密钥为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
)?
这似乎是NSURLCredential
的未记录行为:当将nil
作为密码传递给credentialWithUser:password:persistence:
,并使用此凭据来响应身份验证质询时,iOS会完全忽略该凭据。
解决方案是在您不想使用密码时用空的NSString
( @""
)替换nil
。
所以你的代码应该是这样的:
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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.