这是我在使用 NTLM 身份验证处理 API 时发现的解决方案。本质上,您需要将 URLSessionConfiguration 实例的委托设置为 ViewController 的类(或任何 NSObject 的子类)并实现 URLSessionDelegate 协议的 func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) 函数。
身份验证的处理方式是,当URLSession 发出请求时,它首先协商身份验证方法(参见NSURLProtectionSpace Authentication Method Constants),然后根据您选择的身份验证方法(在这种情况下,我们拒绝所有不是@987654327 @),我们通过服务器进行身份验证。
以下代码已使用 Swift 5.1 和 Xcode 11 进行了测试:
import Cocoa
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
class NTLMAuthentication: NSObject {
private let baseURL = "<insert base URL here>"
private let username: String
private let password: String
lazy private var session: URLSession = {
let config = URLSessionConfiguration.default
return URLSession(configuration: config, delegate: self, delegateQueue: nil)
}()
init(username: String, password: String) {
self.username = username
self.password = password
}
func authenticate() {
let url = URL(string: baseURL)
let request = URLRequest(url: url!)
let task = session.dataTask(with: request) { data, response, error in
guard error == nil else {
print("An error occurred")
return
}
let htmlData = String(bytes: data!, encoding: String.Encoding.utf8)
print(htmlData)
}
task.resume()
}
}
extension NTLMAuthentication : URLSessionDelegate {
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
print("got challenge")
print(challenge.protectionSpace.authenticationMethod)
guard challenge.previousFailureCount == 0 else {
print("too many failures")
completionHandler(.cancelAuthenticationChallenge, nil)
return
}
guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodNTLM else {
completionHandler(.rejectProtectionSpace, nil)
return
}
let credentials = URLCredential(user: self.username, password: self.password, persistence: .forSession)
completionHandler(.useCredential, credentials)
}
}
请注意,PlaygroundPage.current.needsIndefiniteExecution = true 行是在 Playground 中运行此代码所必需的,否则代码将无法在 Playground 终止之前完成运行。