使用客户端证书与 Alamofire 进行身份验证
Posted
技术标签:
【中文标题】使用客户端证书与 Alamofire 进行身份验证【英文标题】:Using client certificate for authentication with 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")
但我还没有找到用证书初始化凭证的方法。是否可以?
【问题讨论】:
【参考方案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。
对于有同样问题的人,这最终帮助了我:***.com/questions/39985856/…以上是关于使用客户端证书与 Alamofire 进行身份验证的主要内容,如果未能解决你的问题,请参考以下文章