2017-02-28 64 views
0

我在Swift中苦於基本身份驗證。Swift 3中的基本身份驗證不起作用

我有一個通過SSL和基本認證的休息後端服務。我的objective-c客戶端代碼運行良好,但相應的Swift無法工作,因爲身份驗證失敗。

這是銀行代碼:

let sUrl = "HTTPS://localhost:8443/Test_1/rest/Service/returnInfo" 
let url: URL = URL(string: sUrl)! 
let request: URLRequest = URLRequest(url: url); 
let session: URLSession = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: OperationQueue()) 
let task: URLSessionDataTask = session.dataTask(with: request) { (data, response, inError) in { 

    ... 
    let httpResponse = response as! HTTPURLResponse 
    if (httpResponse.statusCode != 200) { 
     let details = [NSLocalizedDescriptionKey: "HTTP Error"] 
     let error = NSError(domain:"WS", code:httpResponse.statusCode, userInfo:details) 
     completionHandler(nil, error); 
     return 
    } 
    ... 
} 
task.resume() 

委託方法非常類似於相應的方法在Objective-C:

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

    guard challenge.previousFailureCount == 0 else { 
     challenge.sender?.cancel(challenge) 
     // Inform the user that the user name and password are incorrect 
     completionHandler(.cancelAuthenticationChallenge, nil) 
     return 
    } 

    let proposedCredential = URLCredential(user: user!, password: password!, persistence: .none) 
    completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, proposedCredential) 
} 

的httpResponse.statusCode總是。

委託方法只被調用一次,而Objective-c中的相應方法被調用兩次。

我在哪裏錯了?

UPDATE 相應Objective-C代碼:

NSString *sUrl = [NSString stringWithFormat:@"HTTPS://localhost:8443/Test_1/rest/Service/returnInfo"]; 
NSURL *url = [NSURL URLWithString:sUrl]; 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration]; 
NSURLSession *session = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate:self delegateQueue:[NSOperationQueue mainQueue]]; 
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *inError) { 
    if (inError != nil) { 
     completionHandler(0, inError); 
     return; 
    } 
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; 
    if (httpResponse.statusCode != 200) { 
     NSDictionary *details = @{NSLocalizedDescriptionKey:@"HTTP Error"}; 
     NSError *error = [NSError errorWithDomain:@"WS" code:httpResponse.statusCode userInfo:details]; 
     completionHandler(0, error); 
     return; 
    } 
    NSError *jsonError; 
    NSDictionary *valueAsDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError]; 
    if (jsonError != nil) { 
     completionHandler(0, jsonError); 
     return; 
    } 
    if (![valueAsDictionary[@"ret"] boolValue]) { 
     NSInteger code = [valueAsDictionary[@"code"] integerValue]; 
     NSDictionary *details = @{NSLocalizedDescriptionKey:(valueAsDictionary[@"message"]!=nil) ? valueAsDictionary[@"message"] : @""}; 
     NSError *error = [NSError errorWithDomain:@"WS" code:code userInfo:details]; 
     completionHandler(0, error); 
     return; 
    } 
    completionHandler(valueAsDictionary[@"value"], nil); 
}]; 
[task resume]; 

這是委託功能:

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler { 

if ([challenge previousFailureCount] == 0) { 
    NSURLCredential *newCredential = [NSURLCredential credentialWithUser:_user password:_password persistence:NSURLCredentialPersistenceNone]; 
     completionHandler(NSURLSessionAuthChallengeUseCredential, newCredential); 
} else { 
    completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil); 
} 

} 

回答

0

根據你的問題,這是您的請求(線)實例。

let request:URLRequest = URLRequest(url:url);

這裏沒有爲您的請求實例設置任何頭參數。請將請求標頭和正文參數與您的客戶C客戶端進行比較。

頭部參數可能包括 - 內容類型以及其他有用的保密參數,如API密鑰也。

檢查你的目標C客戶端的請求,並設置相同的PARAMS在你這裏SWIFT代碼

+0

他們是完全一樣的。我已經刪除了一些代碼來簡化問題。此外,禁用服務器上的基本身份驗證,在Swift中一切正常。 – Fab

+0

請在這裏分享/更新您的請求參數的缺失信息,如果它不是機密的。所以我可以指導你正確的方向。據我所知,這是不足以生成Web服務器請求的代碼。你能在這裏分享客觀來源嗎? – 2017-02-28 13:20:45

+0

沒有缺失的信息,無論如何,我更新了我的問題與服務的URL和相應的目標C代碼 – Fab

1

我最終設法使其在斯威夫特的工作,即使我不知道,因爲它沒有工作之前。 顯然,用戶和密碼必須顯式添加到HTTP標頭。

let sUrl = "HTTPS://localhost:8443/Test_1/rest/Service/returnInfo" 
let url: URL = URL(string: sUrl)! 
let request: URLRequest = URLRequest(url: url); 

// Changes from here ... 

let config = URLSessionConfiguration.default 
let userPasswordData = "\(user!):\(password!)".data(using: .utf8) 
let base64EncodedCredential = userPasswordData!.base64EncodedString(options: Data.Base64EncodingOptions.init(rawValue: 0)) 
let authString = "Basic \(base64EncodedCredential)" 
config.httpAdditionalHeaders = ["Authorization" : authString] 
let session: URLSession = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue()) 

// ... to here 

let task: URLSessionDataTask = session.dataTask(with: request) { (data, response, inError) in { 

    ... 
    let httpResponse = response as! HTTPURLResponse 
    if (httpResponse.statusCode != 200) { 
     let details = [NSLocalizedDescriptionKey: "HTTP Error"] 
     let error = NSError(domain:"WS", code:httpResponse.statusCode, userInfo:details) 
     completionHandler(nil, error); 
     return 
    } 
    ... 
} 
task.resume() 
0

此代碼是在迅速3.0.1爲我工作, 希望這對您有所幫助..

let login = "username" 
    let password = "password" 

    let sUrl = NSURL(string: (urlString as NSString) as String) 
    let request: URLRequest = URLRequest(url: sUrl as! URL); 

    let config = URLSessionConfiguration.default 
    let userPasswordData = "\(login):\(password)".data(using: .utf8) 
    let base64EncodedCredential = userPasswordData!.base64EncodedString(options: Data.Base64EncodingOptions.init(rawValue: 0)) 
    let authString = "Basic \(base64EncodedCredential)" 
    config.httpAdditionalHeaders = ["Authorization" : authString] 
    let session: URLSession = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue()) 

    let task = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in 
     print("response \(data)") 

     let httpResponse = response as! HTTPURLResponse 
     if (httpResponse.statusCode != 200) { 
      print(error?.localizedDescription as Any) 
      print("Handle Error") 
     } 
     else{ 
      do { 
       if let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary { 
        print("Synchronous\(jsonResult)") 
       } 
      } catch let error as NSError { 
       print(error.localizedDescription) 
      } 
     } 
    } 
     task.resume() 
    }