swift实现https客户端认证(mac app)
2020-10-12 本文已影响0人
w_j_y
使用私钥和证书进行https客户端认证
网上给的一些客户端认证的方法,在mac app上效果不太好,例如需要生成p12证书、使用时会弹出授权使用私钥的系统提示。
研究了下苹果的官方文档,以下是完美的解决方案
私钥和证书加载类
import Cocoa
class IdentityUtil{
private static var identity: IdentityAndTrust?
public static func loadIdentity() -> IdentityAndTrust{
if(identity != nil){
return identity!
}else{
identity = extractIdentity()
return identity!
}
}
//获取客户端证书相关信息
static func extractIdentity() -> IdentityAndTrust{
loadKey()
return loadPem()
}
//加载证书
static func loadPem()-> IdentityAndTrust{
let pem =
"MIIC/jCCAeagA... 你的客户端证书(需去除首位的-----BEGIN CERTIFICATE-----和-----END CERTIFICATE------,以及去除换行)...cuY2cg="
let certData = Data(base64Encoded: pem)!
let certificate: SecCertificate = SecCertificateCreateWithData(nil,certData as CFData)!
var identity: SecIdentity?
SecIdentityCreateWithCertificate(nil, certificate, &identity)
let certArray = [ certificate ]
var trust: SecTrust?
SecTrustCreateWithCertificates(certArray as AnyObject,SecPolicyCreateBasicX509(),&trust)
return IdentityAndTrust(identityRef: identity!,trust:trust!,certArray: certArray)
}
//加载私钥
static func loadKey(){
let keyBase64 = "MIIEowIBAAKCAQ...你的私钥(需要去除首尾的-----BEGIN PRIVATE KEY-----和-----END PRIVATE KEY-----,以及去除换行) ...MnMOc+wl"
let keyData = Data(base64Encoded: keyBase64)!
let tag = "com.wjy.mykey".data(using: .utf8)!
let key = SecKeyCreateWithData(keyData as NSData, [
kSecAttrKeyType: kSecAttrKeyTypeRSA,
kSecAttrApplicationTag as String: tag,
kSecAttrKeyClass: kSecAttrKeyClassPrivate,
] as NSDictionary, nil)!
let addquery: [String: Any] = [kSecClass as String: kSecClassKey,
kSecAttrApplicationTag as String: tag,
kSecAttrKeyType as String:kSecAttrKeyTypeRSA,
kSecValueRef as String: key]
SecItemAdd(addquery as CFDictionary, nil)
// SecItemDelete(addquery as CFDictionary)
}
}
//认证数据结构体
struct IdentityAndTrust {
var identityRef:SecIdentity
var trust:SecTrust
var certArray:[SecCertificate]
}
URLSession代理类
import Cocoa
class ClientCertificateDelegate: NSObject, NSApplicationDelegate,URLSessionDelegate {
var identity: IdentityAndTrust!
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition,
URLCredential?) -> Void) {
//认证服务器(这里不使用服务器证书认证,只需地址是我们定义的几个地址即可信任)
if challenge.protectionSpace.authenticationMethod
== NSURLAuthenticationMethodServerTrust {
print("服务器认证!")
let credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
completionHandler(.useCredential, credential)
}else if challenge.protectionSpace.authenticationMethod
== NSURLAuthenticationMethodClientCertificate {
print("客户端证书认证!")
//获取客户端证书相关信息
if self.identity == nil{
self.identity = IdentityUtil.loadIdentity()
}
let urlCredential:URLCredential = URLCredential(
identity: self.identity.identityRef,
certificates: nil,
persistence: .none)
completionHandler(.useCredential, urlCredential)
}
}
}
调用接口demo
func getData(){
//1、创建URL
let url: URL = URL(string: "https://xxxx")!
//2、创建URLRequest
let request: URLRequest = URLRequest(url: url)
//3、创建URLSession
let configration = URLSessionConfiguration.default
let session = URLSession(configuration: configration,delegate: ClientCertificateDelegate(), delegateQueue:OperationQueue.main)
//4、URLSessionTask子类
let task: URLSessionDataTask = session.dataTask(with: request) { (data, response, error) in
if error == nil {
DispatchQueue.main.async {
if let data = data {
//得到数据,回到主线程
DispatchQueue.main.async {
//更新界面
}
//完成
return
}
}
}
}
//5、启动任务
task.resume()
}