2016-08-01 100 views
1

我在這裏有這個類,裏面的類是一種方法,我試圖對需要Windows身份驗證用戶名和密碼的API執行NSURLSession。我按照這裏的教程https://gist.github.com/n8armstrong/5c5c828f1b82b0315e24Swift - 用於Windows身份驗證的NSURLSession

以及與此想出了:

let webservice = "https://api.com" 

let config = NSURLSessionConfiguration.defaultSessionConfiguration() 
let urlSession = NSURLSession(configuration: config) 

class WebService: NSObject { 

    func loginUser(username: String, password: String) -> Bool { 

     let userPasswordString = "[email protected]:Password" 
     let userPasswordData = userPasswordString.dataUsingEncoding(NSUTF8StringEncoding) 
     let base64EncodedCredential = userPasswordData!.base64EncodedStringWithOptions([]) 
     let authString = "Basic \(base64EncodedCredential)" 

     config.HTTPAdditionalHeaders = ["Authorization" : authString] 

     let requestString = NSString(format:"%@", webservice) as String 
     let url: NSURL! = NSURL(string: requestString) 

     let task = urlSession.dataTaskWithURL(url) { 
      (let data, let response, let error) in 
      if (response as? NSHTTPURLResponse) != nil { 
       let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding) 
       print(dataString) 
      } 
     } 

     task.resume() 

     return true 

    } 

} 

但是當我運行此我得到一個401錯誤:401 - 未經授權:訪問由於憑據無效被拒絕。

我已經確認API的URL是正確的。與用戶名和密碼相同。我究竟做錯了什麼?

回答

0

我能夠這樣做,以解決這個問題如下:

var credential: NSURLCredential! 

    func loginUser(username: String, password: String) -> Bool { 

     let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() 
     let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil) 

     credential = NSURLCredential(user:username, password:password, persistence: .ForSession) 

     let requestString = NSString(format:"%@", webservice) as String 
     let url: NSURL! = NSURL(string: requestString) 

     let task = session.dataTaskWithURL(url, completionHandler: { 
      data, response, error in 

      dispatch_async(dispatch_get_main_queue(), 
      { 

       if(error == nil) 
       { 
        print("Yay!") 
       } 
       else 
       { 
        print("Naw!") 
       } 

      }) 

     }) 

     task.resume() 

     return true 

    } 

,然後加入NSURLSessionDelegate方法:

func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) { 

     if challenge.previousFailureCount > 0 
     { 
      completionHandler(NSURLSessionAuthChallengeDisposition.CancelAuthenticationChallenge, nil) 
     } 
     else 
     { 
      completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, NSURLCredential(forTrust:challenge.protectionSpace.serverTrust!)) 
     } 

    } 

    func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) { 

     completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential,credential) 

    } 
+0

權。您應該避免重寫授權標頭,因爲NSURLSession保留踩踏它的權利。在某些情況下,您可以使用X-Authorization或類似方法解決此問題,具體取決於服務支持的方式,但執行基本身份驗證的正確方法是創建證書並讓操作系統像您一樣處理它。 – dgatwood