Alamofire 5替代sessionDidReceiveChallenge

人气:882 发布:2022-10-16 标签: https ios swift alamofire alamofire5

问题描述

我刚转移到Alamofire 5.

I have just shifted to Alamofire 5.

之前,我使用URLSession和证书固定器,并且为了处理身份验证挑战,我使用了具有哈希值

Earlier I used URLSession and Certificate Pinner and to handle auth challenge I used delegate method of URLSessionDelegate with hash values

func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge,
                completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
    print("being challanged! for \(challenge.protectionSpace.host)")
    guard let trust = challenge.protectionSpace.serverTrust else {
        print("invalid trust!")
        completionHandler(.cancelAuthenticationChallenge, nil)
        return
    }

    let credential = URLCredential(trust: trust)

    let pinner = setupCertificatePinner(host: challenge.protectionSpace.host)

    if (!pinner.validateCertificateTrustChain(trust)) {
        print("failed: invalid certificate chain!")
        challenge.sender?.cancel(challenge)
    }

    if (pinner.validateTrustPublicKeys(trust)) {
        completionHandler(.useCredential, credential)
    } else {
        didPinningFailed = true
        print("couldn't validate trust for \(challenge.protectionSpace.host)")
        completionHandler(.cancelAuthenticationChallenge, nil)
    }

}

已经转移到Alamofire 5,没有早期版本中可用的方法sessionDidReceiveChallenge.

Having moved to Alamofire 5, there is no method sessionDidReceiveChallenge which was available in earlier version.

我尝试过:

private let session: Session = {
    let manager = ServerTrustManager(allHostsMustBeEvaluated: true, evaluators:
        ["devDomain.com": DisabledTrustEvaluator(),
         "prodDomain.com": PublicKeysTrustEvaluator()])
    let configuration = URLSessionConfiguration.af.default

    return Session(configuration: configuration, serverTrustManager: manager)
}()

但是我得到了错误:

Error Domain=Alamofire.AFError Code=11 "Server trust evaluation failed due to reason: No public keys were found or provided for evaluation."

更新: 我还是更喜欢仅使用256个指纹来解析它的方法,因为我们会在第一个api调用中获得域及其哈希.

Update: I'd still prefer a way to parse it using 256 fingerprint only, as we get domains and its hashes in first api call.

推荐答案

首先,您需要一个ServerTrustEvaluating来处理固定一个简单工具的证书,这类似于

First you need a ServerTrustEvaluating that handle the certificate pinning a simple implement would be something similar to

public final class CertificatePinnerTrustEvaluator: ServerTrustEvaluating {

    public init() {}

    func setupCertificatePinner(host: String) -> CertificatePinner {

        //get the CertificatePinner
    }

    public func evaluate(_ trust: SecTrust, forHost host: String) throws {

        let pinner = setupCertificatePinner(host: host)

        if (!pinner.validateCertificateTrustChain(trust)) {
            print("failed: invalid certificate chain!")
            throw AFError.serverTrustEvaluationFailed(reason: .noCertificatesFound)
        }

        if (!pinner.validateTrustPublicKeys(trust)) {
            print ("couldn't validate trust for \(host)")

            throw AFError.serverTrustEvaluationFailed(reason: .noCertificatesFound)
        }
    }
}

为了能够使用相同的评估器,我建议将ServerTrustManager子类化,以返回我这样做的相同评估器:

To be able to use the same evaluator I would suggest to subclass ServerTrustManager to return the same evaluator I did it like this:

class CertificatePinnerServerTrustManager: ServerTrustManager {

    let evaluator = CertificatePinnerTrustEvaluator()

    init() {
        super.init(allHostsMustBeEvaluated: true, evaluators: [:])
    }

    open override func serverTrustEvaluator(forHost host: String) throws -> ServerTrustEvaluating? {

        return evaluator
    }
}

之后,您应该准备好创建会话并将管理器传递给它

after that you should be ready to go by creating the session and passing the manager to it

private let session: Session = {

    let trustManager = CertificatePinnerServerTrustManager()

    return Session(serverTrustManager: trustManager)
}()

我的参考文献是SessionDelegate.swift中Alamofire源代码中的方法urlSession(_:task:didReceive:completionHandler:),位于第86行(Alamofire V5.2.1)

My reference was the method urlSession(_:task:didReceive:completionHandler:) in Alamofire source in SessionDelegate.swift at line 86 (Alamofire V5.2.1)

351