我设置了一个 Cocoa 类,我想用它连接到我正在构建的 RESTful Web 服务。我决定像这样在我的 PHP 后端上使用 HTTP 基本身份验证......
<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
//Stuff that users will see if they click 'Cancel'
exit;
}
else {
//Validation Code
echo "You entered info.";
}
?>
此时我使用的是同步 NSURLConnection,据我了解 Apple 文档状态对身份验证的支持较少。
但这有可能吗?我可以非常轻松地进行 cookie 身份验证,无需 NSURLProtectionSpaces 或 NSURLCredentials 或任何身份验证类。另外,是否有任何资源可供我阅读有关 Cocoa 身份验证类的更多信息?
谢谢。
更新:mikeabdullahuk 您提供的代码(第二个示例)与我编写的代码几乎相同。我做了更多调查,发现 NSURLConnection 正在返回一个错误……
Error Domain=NSURLErrorDomain Code=-1012 UserInfo=0x1a5170 "Operation could not be completed. (NSURLErrorDomain error -1012.)"
代码对应NSURLErrorUserCancelledAuthentication。所以显然我的代码没有访问 NSURLCredentialStorage 而是取消了身份验证。这与 PHP HTTP 身份验证功能有什么关系吗?在这一点上我很困惑。
最佳答案
同步 NSURLConnection
绝对可以与 NSURLCredentialStorage
一起使用。以下是通常的工作方式:
NSURLConnection
从服务器请求页面- 服务器回复 401 响应
NSURLConnection
查看它可以从 URL 中收集到哪些凭据- 如果 URL 没有提供完整的凭据(用户名和密码),
NSURLConnection
也会引用NSURLCredentialStorage
来填补空白< - 如果完整的凭据仍未确定,
NSURLConnection
将发送-connection:didReceiveAuthenticationChallenge:
委托(delegate)方法请求凭据 - 如果
NSURLConnection
现在终于有了完整的凭据,它会重试包含授权数据的原始请求。
通过使用同步连接方法,您仅在第 5 步中失去了提供自定义身份验证的能力。因此,您可以在 URL 中预先提供身份验证凭据,或者在发送请求之前将它们放在 NSURLCredentialStorage
中。例如
NSURLRequest *request =
[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://user:pass@example.com"]];
[NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:NULL];
或:
NSURLCredential *credential = [NSURLCredential credentialWithUser:@"user"
password:@"pass"
persistence:NSURLCredentialPersistenceForSession];
NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc]
initWithHost:@"example.com"
port:0
protocol:@"http"
realm:nil
authenticationMethod:nil];
[[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:credential
forProtectionSpace:protectionSpace];
[protectionSpace release];
NSURLRequest *request =
[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://example.com"]];
[NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:NULL];
关于objective-c - 我可以使用 NSURLCredentialStorage 进行 HTTP 基本身份验证吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/501231/