简体   繁体   English

URLSession不适用于URLCredential

[英]URLSession not working with URLCredential

I have an API I am trying to connect to and the server is Windows Authentication. 我有一个我想连接的API,服务器是Windows身份验证。

I am trying to use URLSession with URLCredential with the delegate methods 我正在尝试将URLSession与URLCredential一起使用委托方法

func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void){

        var disposition: URLSession.AuthChallengeDisposition = URLSession.AuthChallengeDisposition.performDefaultHandling

        var credential:URLCredential?

        print(challenge.protectionSpace.authenticationMethod)

        if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
            credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)

            if (credential != nil) {
                disposition = URLSession.AuthChallengeDisposition.useCredential
            }
            else
            {
                disposition = URLSession.AuthChallengeDisposition.performDefaultHandling
            }
        }
        else
        {
            disposition = URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge
        }

        completionHandler(disposition, credential);
    }

This code runs twice as after doing some printing is because there are two Authentication Methods: 执行某些打印后,此代码运行两次,因为有两种身份验证方法:

NSURLAuthenticationMethodServerTrust and NSURLAuthenticationMethodNTLM when it runs through the NSURLAuthenticationMethodServerTrust everything is fine, but when it runs NSURLAuthenticationMethodNTLM I get an error on this line: NSURLAuthenticationMethodServerTrust和NSURLAuthenticationMethodNTLM在通过NSURLAuthenticationMethodServerTrust运行时一切正常,但是当它运行NSURLAuthenticationMethodNTLM时,我在此行上收到错误:

credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)

saying this: 这样说:

fatal error: unexpectedly found nil while unwrapping an Optional value

but only when I change this condition from 但只有当我改变这个条件时

if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {

to

if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodNTLM {

What Am I doing wrong? 我究竟做错了什么?

Here is the method I am using to try to connect to that API 这是我用来尝试连接到该API的方法

func loginUser(_ username: String, password: String, completion: @escaping (_ result: Bool) -> Void)
    {
        //Create request URL as String

        let requestString = String(format:"%@", webservice) as String

        //Covert URL request string to URL

        guard let url = URL(string: requestString) else {
            print("Error: cannot create URL")
            return
        }

        //Convert URL to URLRequest

        let urlRequest = URLRequest(url: url)

        print(urlRequest)

        //Add the username and password to URLCredential

        credentials = URLCredential(user:username, password:password, persistence: .forSession)

        print(credentials)

        //Setup the URLSessionConfiguration

        let config = URLSessionConfiguration.default

        //Setup the URLSession

        let session = URLSession(configuration: config, delegate: self, delegateQueue: nil)

        //Prepare the task to get data.

        let task = session.dataTask(with: urlRequest, completionHandler: { (data, response, error) in

            DispatchQueue.main.async(execute: {

                print(error!)

                if(error == nil)
                {
                    completion(true)
                }
                else
                {
                    completion(false)
                }

            })

        })

        //Run the task to get data.

        task.resume()

    } 

In the Apple documentation for URLProtectionSpace.serverTrust , it says: URLProtectionSpace.serverTrustApple文档中 ,它说:

nil if the authentication method of the protection space is not server trust. 如果保护空间的身份验证方法不是服务器信任,则为nil。

So, you are trying to unwrap an optional value of nil , which of course would cause a crash. 所以,你试图解开一个可选的nil值,这当然会导致崩溃。

In your case, you could probably just replace the entire function with (untested): 在您的情况下,您可能只需用(未经测试)替换整个函数:

func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void){

    var disposition: URLSession.AuthChallengeDisposition = URLSession.AuthChallengeDisposition.performDefaultHandling

    print(challenge.protectionSpace.authenticationMethod)

    if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
        disposition = URLSession.AuthChallengeDisposition.performDefaultHandling
    }
    else
    {
        disposition = URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge
    }

    completionHandler(disposition, credential);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM