Swift 3中的基本身份验证不起作用 [英] Basic Authentication in Swift 3 does't work

查看:106
本文介绍了Swift 3中的基本身份验证不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Swift中的基本身份验证.

I am struggling with basic authentication in Swift.

我有一个通过SSL和基本身份验证的Rest后端服务.我的Objective-C客户端代码运行良好,但由于身份验证失败,相应的Swift代码不起作用.

I have a Rest back end service over SSL and with basic authentication. My objective-c client code works well but the corresponding Swift one doesn't work because the authentication fails.

这是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中的相应方法非常相似:

The delegate method is quite similar to the corresponding method in 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始终为 401 .

The httpResponse.statusCode is always 401.

委托方法仅被调用一次,而Objective-c中相应的方法被调用两次.

The delegate method is called only once, instead the corresponding method in Objective-c is called two times.

我在哪里错了?

更新 相应的Objective-c代码:

UPDATE The corresponding Objective-c code:

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中工作,即使我不知道,因为以前它不工作. 显然,必须将用户名和密码显式添加到HTTP标头中.

I eventually managed to make it working in Swift, even if I don't know because it was not working before. Apparently, user and password have to be explicitly added to the HTTP headers.

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

这篇关于Swift 3中的基本身份验证不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆