【发布时间】:2016-10-22 19:16:19
【问题描述】:
我正在对服务器进行后期调用,但一直收到服务器证书无效的错误消息,因此经过研究,我发现我必须使用身份验证质询来信任服务器。这一切都很好(我打印了身份验证质询以确保它确实如此)但其余的调用没有通过,我无法从我的服务器获取信息,身份验证质询后没有任何反应,通常我希望被返回数据。然而,什么都没有发生,我的 urlsessiondatadelegates 都没有被调用(检查中断)。
任何人都可以找出原因吗?代码:
var request = URLRequest(url: URL(string: "https://45.56.105.97:7915/search-v2")!)
request.httpMethod = "POST"
request.addValue("Basic ***********", forHTTPHeaderField: "Authorization")
let task = URLSession(configuration: .default, delegate: self, delegateQueue: OperationQueue.main)
task.dataTask(with: request) { (data, response, error) in
print(error)
print(data)
if let responseData = NSString(data: data!, encoding: String.Encoding.utf8.rawValue){
print("data: \(responseData)")
self.parseXML(data!)
}
}.resume()
委托方法:
func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
print("did autherntcationchallenge = \(challenge.protectionSpace.authenticationMethod)")
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
print("send credential Server Trust")
let credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
challenge.sender!.use(credential, for: challenge)
}else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPBasic{
print("send credential HTTP Basic")
let defaultCredentials: URLCredential = URLCredential(user: "username", password: "password", persistence:URLCredential.Persistence.forSession)
challenge.sender!.use(defaultCredentials, for: challenge)
}else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodNTLM{
print("send credential NTLM")
} else{
challenge.sender!.performDefaultHandling!(for: challenge)
}
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
print("Data received: \(data)")
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
print("Response received: \(response)")
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
print("something went wrong: \(error)")
}
func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
print("rep: \(response)")
}
运行后,我得到的只是:
是否 autherntcationchallenge = NSURLAuthenticationMethodServerTrust 发送凭据服务器信任
我还看到了关于我如何只能使用闭包或委托方法来检索数据/不能同时使用两者的对话。我已经尝试了一切都没有成功。
**我也知道我不应该只是盲目地信任服务器,但我试图弄清楚为什么我无法接收到数据,我知道这存在严重的安全漏洞。
【问题讨论】:
-
当这些委托方法提供完成处理程序时,您必须调用该完成处理程序,否则连接将无法继续。
-
是否调用了“urlsessiondatadelegates”,如果调用了,请分享您的代码?
标签: ios swift authentication nsurlsession