为了我的应用程序通信,我正在从NSURLConnection切换到NSURLSession,并且在进行应用程序通信时,我试图从委托身份验证转向使用NSURLCredentialStorage。但是,尽管在应用程序启动时已经在-URLSession:task:didReceiveChallenge上设置了defaultCredentials,但我还是在委托上调用了sharedCredentialStorage。
按照以下记录的消息,保护空间是相同的(我在设置凭据时创建的保护空间与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委托方法期间:
po [[NSURLCredentialStorage sharedCredentialStorage] defaultCredentialForProtectionSpace:[challenge protectionSpace]]结果:
<NSURLCredential: 0x1680ff00>: thecorrectusernamehttps://stackoverflow.com/a/501869/563905表示,当服务器响应401挑战时,NSURLConnection (这是NSURLSession问题吗?)首先检查授权的头(没有设置),然后咨询NSURLCredentialStorage以获得保护空间的凭据。
我只是不明白为什么要叫didReceiveChallenge代表?当我没有设置委托方法时,NSURLSession只是在没有任何凭据的情况下重新发送请求.我被困住了..。
编辑:我在didReceiveChallenge:方法中添加了手动凭证处理,尽管只使用了一个NSURLSession,但每个请求都会触发它。
发布于 2014-11-07 17:10:53
我只是遇到了同样的问题,我的URLSession不使用存储的凭据。然后,我阅读了NSURLSession的参考文档。基本上,它的意思是,如果您正在实现一个自定义委托,那么在调用委托方法时,您必须自己处理所有内容。换句话说,保存证书是战斗的一半。每次服务器需要身份验证时,您都会收到挑战,因此,在didReceiveChallenge方法中,您现在必须手动提取使用的凭据,并将它们传递给完成处理程序。如果这有意义的话请告诉我。
发布于 2018-05-10 07:21:56
您需要使用NSURLSessionTaskDelegate或NSURLSessionDelegate。
//这是基本凭据的https://developer.apple.com/documentation/foundation/nsurlsessiontaskdelegate/1411595-urlsession
或
//用于会话级别的挑战-level身份验证方法is、NSURLAuthenticationMethodNegotiate、NSURLAuthenticationMethodClientCertificate或NSURLAuthenticationMethodServerTrust https://developer.apple.com/documentation/foundation/nsurlsessiondelegate/1409308-urlsession
例如:
@interface MySessionClass : URLSession <URLSessionTaskDelegate>
@end
@implementation MySessionClass
#pragma mark - Delegate
//That method will call one time if you use NSURLCredentialPersistencePermanent but if you use other type that method it will call all the time.
- (void) URLSession:(NSURLSession *)session
task:(NSURLSessionTask *)task
didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler {
if (challenge.previousFailureCount == 0) {
NSURLCredential *credential = [NSURLCredential credentialWithUser:self.user password:self.password persistence:NSURLCredentialPersistencePermanent];
completionHandler(NSURLSessionAuthChallengeUseCredential, credentials);
} else {
completionHandler(NSURLSessionAuthChallengeRejectProtectionSpace, nil);
}
}
@endhttps://stackoverflow.com/questions/25756611
复制相似问题