使用身份验证连接到站点时,SWIFT 3 NSURLSession/NSURLConnection HTTP加载失败 [英] Swift 3 NSURLSession/NSURLConnection HTTP load failed when connecting to a site with authentication

查看:0
本文介绍了使用身份验证连接到站点时,SWIFT 3 NSURLSession/NSURLConnection HTTP加载失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以前见过这个错误,补救方法似乎是向.plist文件中添加信息。我看过的每一款我都试过了:

How do I load an HTTP URL with App Transport Security enabled in iOS 9?

NSURLSession/NSURLConnection HTTP load failed on iOS 9

NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9802) on a subdomain?

我的程序仍然会抛出相同的错误:

2017-05-08 08:29:37.781075-0400xxxx[3256:408961][]nw_coretls_callback_handshake_message_block_invoke_3 tls_握手_继续:[-9812] 2017年05月08日08:29:37.781 xxxx[3256:408982]NSURLSession/NSURLConnection http加载失败(kCFStreamErrorDomainSSL,-9813)

我的相关代码如下:

    let username = "xxxx"
    let password = "xxxx"
    let loginString = String(format: "%@:%@", username, password)
    let loginData = loginString.data(using: String.Encoding.utf8)!
    let base64LoginString = loginData.base64EncodedString()

    let baseUrl = "https://xxxx"
    var request = URLRequest(url: URL(string: baseUrl)! as URL)

let baseUrl = "server i want.xml"
        let request = NSMutableURLRequest(url: NSURL(string: baseUrl)! as URL)
        request.httpMethod = "POST"
        request.setValue("Basic (base64LoginString)", forHTTPHeaderField: "Authorization")
        let session = URLSession.shared

        var err: NSError?

        let task = session.dataTask(with: request as URLRequest) {
            (data, response, error) in

            if data == nil {
                print("dataTaskWithRequest error: (err)")
                return
            }

            let xml = SWXMLHash.parse(data!)
            let serialNumFromXML = xml["mobile_devices"]["mobile_device"]["serial_number"].element?.text

func urlSession(
    _ session: URLSession,
    didReceive challenge: URLAuthenticationChallenge,
    completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
{
    completionHandler(
        .useCredential,
        URLCredential(trust: challenge.protectionSpace.serverTrust!))
}

我看到它可能与证书有关,但我不能更改服务器,因为我不负责它,所以我无法获得适当的证书。除了更改拼写外,还有其他事情要做吗?

我的plist文件具有允许任意加载和我的XML文件所在域的异常域。

我可以获得测试文件的内容,如https://www.w3schools.com/xml/note.xml,但我需要的文件在用户名/密码"需要身份验证"弹出窗口的后面。

我也试过Alamofire库,同样的情况也发生了:

nw_coretls_callback_handshake_message_block_invoke_3 TLS_HANDSHAK_CONTINUE:[-9807] 2017年05月08日09:42:08.452 xxx[6128:888398]NSURLSession/NSURLConnection http加载失败(kCFStreamErrorDomainSSL,-9802)

推荐答案

好吧,我不知道如何修复这个问题,但我发现Alamofire可以用来做我需要的事情。这是一个本地的库存管理项目,所以我不担心绕过证书的安全性。我的代码如下:

       Manager.delegate.sessionDidReceiveChallenge = { session, challenge in
        var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
        var credential: URLCredential?

        if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust, let trust = challenge.protectionSpace.serverTrust {
            disposition = URLSession.AuthChallengeDisposition.useCredential
            credential = URLCredential(trust: trust)
        } else {
            if challenge.previousFailureCount > 0 {
                disposition = .cancelAuthenticationChallenge
            } else {
                credential = Manager.session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)

                if credential != nil {
                    disposition = .useCredential
                }
            }
        }

        return (disposition, credential)
    }

private var Manager: Alamofire.SessionManager = {

// Create the server trust policies
let serverTrustPolicies: [String: ServerTrustPolicy] = [
    "https://SERVER:PORT": .disableEvaluation
]

// Create custom manager
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = Alamofire.SessionManager.defaultHTTPHeaders
let manager = Alamofire.SessionManager(
    configuration: URLSessionConfiguration.default,
    serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
)
let sessionManager = SessionManager(
    serverTrustPolicyManager: ServerTrustPolicyManager(
        policies: ["https://SERVER:PORT": .disableEvaluation]
    )
)
return manager
}()

open class MyServerTrustPolicyManager: ServerTrustPolicyManager {

// Override this function in order to trust any self-signed https
open override func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? {
    return ServerTrustPolicy.disableEvaluation
 }

}

这篇关于使用身份验证连接到站点时,SWIFT 3 NSURLSession/NSURLConnection HTTP加载失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆