无法使用 Alamofire 5.0.2 应用证书固定

Failed to apply certificate pinning with Alamofire 5.0.2

我正在迁移我的应用程序以使用 Alamofire 5.0.2,在过去的版本中它使用 Alamofire 4.x 并且证书固定工作正常。

然后我通过这些更改迁移了 Alamofire 及其证书固定配置:


//Usage example of the function `defaultSessionManager`
class ViewController: UIViewController {

    let sessionManager = defaultSessionManager(defaultRequestInterceptor())
    //...
}

private func defaultSessionManager(_ requestInterceptor: RequestInterceptor?) -> Alamofire.Session {

  let evaluators: [String: ServerTrustEvaluating] = [
    "https://myapp.com": PinnedCertificatesTrustEvaluator(certificates: pinnedCertificates()),
  ]

  let configuration: URLSessionConfiguration = URLSessionConfiguration.af.default
  configuration.timeoutIntervalForRequest = 10 // seconds
  configuration.timeoutIntervalForResource = 10 // seconds

  return Alamofire.Session(
    configuration: configuration,
    interceptor: requestInterceptor,
    serverTrustManager: ServerTrustManager(evaluators: evaluators))
}

func pinnedCertificates() -> [SecCertificate] {

  var certificates: [SecCertificate] = []
  let directoryContents: [URL] = //...

  let certificateName: String = "app.cer" // Replaced for the demo

  let pinnedCertificateURL: URL? = directoryContents.first { (url: URL) in url.lastPathComponent == certificateName }

  if let pinnedCertificateURL: URL = pinnedCertificateURL {
    do {
      let pinnedCertificateData: CFData = try Data(contentsOf: pinnedCertificateURL) as CFData
      if let pinnedCertificate: SecCertificate = SecCertificateCreateWithData(nil, pinnedCertificateData) {
        certificates.append(pinnedCertificate)
      }
    } catch {
        //...
    }
  }
  return certificates
}

使用上述解决方案,我收到错误:

MyApp[374:21470] Task <DDC8F9FD-81A3-EBA4-8AA2-D7C99DD3E63B>.<1> HTTP load failed, 0/0 bytes (error code: -999 [1:89])

如果我删除行 serverTrustManager: ServerTrustManager(evaluators: evaluators)),Alamofire 可以工作但没有证书固定。

知道如何解决这个问题以及我做错了什么吗?

谢谢。

评估器映射中的 String 应该只是主机,而不是完整的 url:

let evaluators: [String: ServerTrustEvaluating] = [
    "myapp.com": PinnedCertificatesTrustEvaluator(certificates: pinnedCertificates()),
  ]

此外,您需要确保主机与您发出请求的域完全匹配。

此外,Alamofire 会自动在您的包中查找证书,因此您可能不需要自己查找。