使用客户端证书通过Alamofire进行身份验证

时间:2018-09-28 00:19:18

标签: ios swift alamofire

我正在开发一个需要在远程服务器上执行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")
          }

但是我还没有找到使用证书初始化证书的方法。可能吗?

1 个答案:

答案 0 :(得分:0)

我不了解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)