2016-12-06 13 views
9

Tôi có một API mà tôi đang cố gắng kết nối và máy chủ là Xác thực Windows.URLSession không hoạt động với URLCredential

Tôi cố gắng để sử dụng URLSession với URLCredential với các phương pháp đại biểu

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); 
    } 

Mã này chạy gấp đôi sau khi làm một số in được vì có hai Authentication Methods:

NSURLAuthenticationMethodServerTrust và NSURLAuthenticationMethodNTLM khi nó chạy thông qua NSURLAuthenticationMethodServerTrust tất cả mọi thứ là tốt, nhưng khi nó chạy NSURLAuthenticationMethodNTLM tôi nhận được một lỗi trên dòng này:

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

nói điều này:

fatal error: unexpectedly found nil while unwrapping an Optional value 

nhưng chỉ khi tôi thay đổi tình trạng này từ

if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { 

để

if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodNTLM { 

Tôi có làm gì sai?

Dưới đây là phương pháp tôi đang sử dụng để cố gắng kết nối với 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() 

    } 
+0

này không thêm lên. Lần đầu tiên bạn nhận được thử thách tin cậy máy chủ, đúng không? do đó, nó sẽ đi vào bên trong điều kiện if, lần thứ hai bạn sẽ nhận được một thách thức NTLM và nó thậm chí không nên đi vào trong điều kiện if nơi bạn đang thiết lập biến ủy nhiệm. Vui lòng thêm câu lệnh in trong mỗi điều kiện if else và sao chép/vượt qua dấu vết ngăn xếp lỗi – nitinsh99

+0

Tôi đã nêu trong câu hỏi của mình rằng tôi có thể vào trong điều kiện bằng NTLM khi tôi cập nhật điều kiện 'if challenge.protectionSpace.authenticationMethod = = NSURLAuthenticationMethodNTLM {' – user979331

+0

Trong trường hợp khi bạn nhận được thử thách với NTLM loại, bạn nên sử dụng thông tin xác thực được tạo bằng tên người dùng và mật khẩu. Bạn có thể xin vui lòng gửi mã nguồn cho trường hợp NTLM. – Ramis

Trả lời

1

rằng Trong Apple documentation for URLProtectionSpace.serverTrust, nó nói:

nil nếu phương thức xác thực của không gian bảo vệ không phải là máy chủ Lòng tin.

Vì vậy, bạn đang cố gắng mở một giá trị tùy chọn là nil, điều này tất nhiên sẽ gây ra sự cố.

Trong trường hợp của bạn, bạn có thể có lẽ chỉ thay thế toàn bộ chức năng với (chưa được kiểm tra):

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); 
} 
+0

@ user979331 Đảm bảo đánh dấu câu trả lời này là được chấp nhận nếu nó hoạt động, bằng cách nhấp vào kiểm tra màu xanh lá cây ở trên cùng bên trái (ngay bên cạnh "Trong trường hợp của bạn ..."). – Coder256

Các vấn đề liên quan