私は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);
}
}
は、彼らはまったく同じです。質問を簡単にするためにいくつかのコードを削除しました。さらに、サーバー上の基本認証を無効にすると、すべてがSwiftでも正常に機能します。 – Fab
機密情報でない場合は、ここにあなたのリクエストパラメータに関する情報が不足しています。だから私はあなたを正しい方向に導くことができます。私の知る限りでは、これはWebサーバー要求を生成するのに十分なコードではありません。ここで客観的な情報源を共有できますか? –
情報が欠落していないとにかく、質問をサービスURLと対応する目的コードに更新しました。 – Fab