【问题标题】:Using client certificate for authentication with Alamofire使用客户端证书与 Alamofire 进行身份验证
【发布时间】:2018-09-28 00:19:18
【问题描述】:

我正在开发一个需要在远程服务器上执行 HTTPS POST 的 iOS 应用程序。这是我想做的:

        // How to initialize 'credential' with a certificate.der (or .pem)
        var credential: URLCredential? 
        let pms: [String: Any] = ["func": "os.getpid"]
        Alamofire.request("https://mytestdomain.mycom/exec", method: .post, 
          parameters: pms, encoding: JSONEncoding.default, headers: nil)
          .authenticate(usingCredential: credential!)
          .responseJSON { response in
          if response.result.isSuccess {
              print("Success")
          }
          else {
              print("Error")
          }

但我还没有找到用证书初始化凭证的方法。是否可以?

【问题讨论】:

    标签: ios swift alamofire


    【解决方案1】:

    我不知道 DER 或 PEM.. 但是对于 p12,您可以这样做:

    private func loadCertificate(name: String, password: String?) throws -> (identity: SecIdentity, certificate: SecCertificate) {
        let path = Bundle.main.path(forResource: name, ofType: "p12")!
        let data = NSData(contentsOfFile: path)!
        let certificate = SecCertificateCreateWithData(nil, data)!
    
        let options = [String(kSecImportExportPassphrase):password ?? ""]
        var items: CFArray? = nil
        let result = SecPKCS12Import(data, options as CFDictionary, &items)
    
        if (result != errSecSuccess) {
            throw RuntimeError("Cannot Import Certificte")
        }
    
        let info = (items! as NSArray).firstObject! as! NSDictionary
        let identity = info[String(kSecImportItemIdentity)] as! SecIdentity
        return (identity, certificate)
    }
    

    然后:

    let info = try loadCertificate(name: "MyCertificate", password: "Password..")
    let credentials = URLCredential(identity: info.identity, certificates: [info.certificate], persistence: .forSession)
    

    【讨论】:

    • 用 p12 试过,得到了这个:Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value 违规代码行:let certificate = SecCertificateCreateWithData(nil, data)!
    • @phoebus 不,我决定转而使用 React-Native。
    • 对于有同样问题的人,这最终帮助了我:stackoverflow.com/questions/39985856/…
    猜你喜欢
    • 2012-01-10
    • 2015-10-29
    • 2018-07-05
    • 2019-01-14
    • 1970-01-01
    • 2012-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多