Swift iOS摘要式身份验证返回401

时间:2019-01-08 17:37:12

标签: swift nsurlsession digest-authentication urlsession

我正在尝试使用通过摘要式身份验证进行身份验证的API端点。我的目标是使用AlamoFire,而是使用标准的URLSession。

首先,我创建请求并启动任务

var request = URLRequest(url: url)
let task = urlSession?.dataTask(with: request, completionHandler: { (data, response, error) in
        // hide network activity
        DispatchQueue.main.async {
            UIApplication.shared.isNetworkActivityIndicatorVisible = false
        }

        // log success/error
        if let method = request.httpMethod, let url = response?.url?.obfuscateForPII() {
            if let error = error {
                DDLogError("\(method) \(url) \(error.localizedDescription)")
            } else {
                DDLogInfo("Success \(method) \(url)")
            }
        }

        // pass endpoint results to completion block
        completionBlock(data, response, error)
    })

    // run the task
    if let task = task {
        task.resume()
    }

我的课程实现了URLSessionDelegate,这是处理挑战的地方

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

    if challenge.previousFailureCount == 0 {
        let keyChainStore = UICKeyChainStore.init(service: kKeychainStore)

        if let username = UserDefaults.standard.value(forKey: kUsername) as? String,
            let password = keyChainStore[kPassword] {

            let credentials = URLCredential(user: username, password: password, persistence: .forSession)

            completionHandler(.useCredential, credentials)
        }

    } else {
        completionHandler(.performDefaultHandling, nil)
    }
}

我的问题是,当我命中端点时,我收到了401响应。当我查看返回的响应时,我看到www-authenticate标头,但是它不包含正确的摘要信息。

如何在不依赖AlamoFire的情况下正确使用经过摘要身份验证的终结点?

0 个答案:

没有答案