我正在为我的应用程序通信从 NSURLConnection 切换到 NSURLSession,并且在我尝试从委托(delegate)身份验证转移到使用 NSURLCredentialStorage 时。我已经移动了代码,但是尽管在应用程序启动时在 sharedCredentialStorage 上设置了 defaultCredentials,但我仍然在委托(delegate)上调用 -URLSession:task:didReceiveChallenge。
根据以下记录的消息,保护空间是相同的(我在设置凭据时创建的空间和由 NSURLAuthenticationChallenge 传递的空间):
Register credentials for: <NSURLProtectionSpace: 0x162227c0>: Host:192.168.1.99, Server:https, Auth-Scheme:NSURLAuthenticationMethodDefault, Realm:192.168.1.99, Port:23650, Proxy:NO, Proxy-Type:(null)
Unexpected authentication challenge: <NSURLProtectionSpace: 0x1680ee40>: Host:192.168.1.99, Server:https, Auth-Scheme:NSURLAuthenticationMethodDefault, Realm:192.168.1.99, Port:23650, Proxy:NO, Proxy-Type:(null)
在 didReceiveChallenge:(NSURLAuthenticationChallenge*)challenge 委托(delegate)方法中:
po [[NSURLCredentialStorage sharedCredentialStorage] defaultCredentialForProtectionSpace:[challenge protectionSpace]]
结果
<NSURLCredential: 0x1680ff00>: thecorrectusername
https://stackoverflow.com/a/501869/563905表明,当服务器响应 401 挑战时,NSURLConnection(这是 NSURLSession 问题吗?)首先检查授权 header (没有任何设置),然后咨询 NSURLCredentialStorage 以获取保护空间的凭据。
我只是不明白为什么要调用 didReceiveChallenge 委托(delegate)?当我没有设置委托(delegate)方法时,NSURLSession 只是在没有任何凭据的情况下重新发送请求......我很难过......
编辑: 我在 didReceiveChallenge: 方法中添加了手动凭证处理,尽管只使用了一个 NSURLSession,但每个请求都会触发它。
最佳答案
我只是遇到了同样的问题,我的 URLSession 不会使用存储的凭据。然后我阅读了 NSURLSession 的引用文档。基本上它说的是,如果你正在实现一个自定义委托(delegate),那么当调用委托(delegate)方法时你必须自己处理所有的事情。换句话说,保存凭据是成功的一半。每次服务器需要身份验证时,您都会收到质询,因此在 didReceiveChallenge 方法中,您现在必须手动提取要使用的凭据并将它们传递给完成处理程序。让我知道这是否有意义。
关于ios - NSURLCredentialStorage 默认凭证不会自动使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25756611/