2017-02-28 6 views
0

私はSwiftの基本認証に苦労しています。Swift 3の基本認証が機能しない

私は、SSLと基本認証でRest Rest Endサービスを持っています。私の目的のクライアントコードは正常に動作しますが、認証が失敗したため、対応する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は常にある

これはスウィフトコードです。

デリゲートメソッドは1回だけ呼び出され、Objective-cの対応するメソッドは2回呼び出されます。

どこが間違っていますか?

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キーのような他の有用な機密パラメータも含めることができます。

+0

は、彼らはまったく同じです。質問を簡単にするためにいくつかのコードを削除しました。さらに、サーバー上の基本認証を無効にすると、すべてがSwiftでも正常に機能します。 – Fab

+0

機密情報でない場合は、ここにあなたのリクエストパラメータに関する情報が不足しています。だから私はあなたを正しい方向に導くことができます。私の知る限りでは、これはWebサーバー要求を生成するのに十分なコードではありません。ここで客観的な情報源を共有できますか? –

+0

情報が欠落していないとにかく、質問をサービスURLと対応する目的コードに更新しました。 – Fab

1

私は最終的にはそれが前に働いていなかったので、私は知っていない場合でも、スウィフトに操作できるように管理し

は、あなたの迅速なコードの中でここにあなたの目的Cクライアントの要求と設定同じのparamsを確認してください。明らかに、HTTPヘッダーにユーザーとパスワードを明示的に追加する必要があります。このコードは、SWIFT 3.0.1で私のために働いている

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

、 希望あなたにこのヘルプ..

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