我需要从Alamofire 4迁移到5,但是我在委托上缺少sessionDidReceiveChallenge
回调
我以前在版本4中使用过这样的内容:
let manager = Alamofire.SessionManager(
configuration: URLSessionConfiguration.default
)
manager.delegate.sessionDidReceiveChallenge = { session, challenge in
let method = challenge.protectionSpace.authenticationMethod
if method == NSURLAuthenticationMethodClientCertificate {
return (.useCredential, self.cert.urlCredential())
}
if method == NSURLAuthenticationMethodServerTrust {
let trust = challenge.protectionSpace.serverTrust!
let credential = URLCredential(trust: trust)
return (.useCredential, credential)
}
return (.performDefaultHandling, Optional.none)
}
但是现在是版本5,委托已更改为SessionDelegate
类,但未提供类似功能
我试图像这样使用URLSession
中的委托:
let delegate = SomeSessionDelegate()
let delegateQueue: OperationQueue = .init()
delegateQueue.underlyingQueue = .global(qos: .background)
let session = URLSession(
configuration: URLSessionConfiguration.af.default,
delegate: delegate,
delegateQueue: delegateQueue
)
let manager = Alamofire.Session(
session: session,
delegate: SessionDelegate(),
rootQueue: .global(qos: .background)
)
class SomeSessionDelegate: NSObject, URLSessionDelegate {
let cert = ...
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
//same impl as before
}
}
我猜我在版本5中的实现是错误的,因为我停止获取响应回调
[请提供有关在版本5中如何正确处理请求质询的建议
SessionDelegate
即可使用客户端证书。 Alamofire将自动使用附加的URLCredential
进行客户端证书挑战。只需将凭证附加到请求:AF.request(...)
.authenticate(with: clientCertCredential)
.response...
此外,您的服务器信任检查将返回任何有效的信任,这可能是安全问题。我将立即停止使用该代码。
URLProtectionSpace
共享存储上的URLCredentialStorage
,然后将其设置为Alamofire.Session
配置这里有一个示例进行设置(端口443可能就足够了]
fileprivate func registerURLCredential() {
let storage = URLCredentialStorage.shared
do {
let credential: URLCredential = try loadURLCredential("certificate", password: "blablabla")
let url = URL.API
let host = url.host ?? ""
let ports: [Int] = [80, 443, url.port ?? 0]
for port in ports {
let space = URLProtectionSpace(
host: host,
port: port,
protocol: url.scheme,
realm: nil,
authenticationMethod: NSURLAuthenticationMethodClientCertificate
)
storage.set(credential, for: space)
}
} catch {
print(error)
}
}
fileprivate func createSession(_ configurationHandler: ((_ configuration: URLSessionConfiguration) -> Void)? = nil) -> Alamofire.Session {
let configuration = URLSessionConfiguration.af.default
registerURLCredential()
configuration.urlCredentialStorage = .shared
configurationHandler?(configuration)
let session = Session(
configuration: configuration,
requestQueue: .global(qos: .background),
serializationQueue: .global(qos: .background)
)
return session
}
一个简单的用途是:
let sesstion = createSession({ configuration in configuration.httpMaximumConnectionsPerHost = 1 })