问题描述
我需要从 Alamofire 4 迁移到 5,但我缺少委托上的 sessionDidReceiveChallenge
回调
I need to migrate from Alamofire 4 to 5 but I'm missing sessionDidReceiveChallenge
callback on the delegate
我之前在第 4 版中使用过这样的东西:
I used before in version 4 something like this:
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
类,但没有提供类似的功能
but now is version 5 the delegate has changed to SessionDelegate
class without providing a similar function
我尝试像这样使用 URLSession
中的委托:
I tried to use the delegate from the URLSession
like this:
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 版中的实现是错误的,因为我停止收到响应回调
I'm guessing that my implementation in version 5 is wrong because I stopped getting response callback
请告知如何在版本 5 中正确管理请求挑战
Please advise on how to manage the request challenge properly in version 5
推荐答案
无需覆盖 SessionDelegate
即可使用客户端证书.Alamofire 将自动使用附加的 URLCredential
进行客户端证书质询.只需将凭据附加到请求中即可:
It isn't necessary to override the SessionDelegate
to use client certificates. Alamofire will automatically use an attached URLCredential
for client certificate challenges. Just attach the credential to the request:
AF.request(...)
.authenticate(with: clientCertCredential)
.response...
此外,您的服务器信任检查会将任何信任返回为有效,这可能是一个安全问题.我会立即停止使用该代码.
Also, your server trust check will return any trust as valid, which could be a security issue. I'd stop using that code immediately.