使用Moya庫,進行https證書校驗

出神入化發表於2018-06-14

查了很多網上的文章,對moya的https證書校驗基本都是略,要麼就是16/17年的程式碼,但是執行的時候找到證書,轉data格式的時候報錯,崩潰; 我用的Moya庫版本號是11的,pod 'Moya', '~> 11.0' 不費話,下面直接看程式碼吧,希望對你們有幫助;

public func defaultAlamofireManager() -> Manager {
   let configuration = URLSessionConfiguration.default
   configuration.httpAdditionalHeaders = Alamofire.SessionManager.defaultHTTPHeaders
   //獲取本地證書
   let path: String = Bundle.main.path(forResource: "證書名", ofType: "cer")!
   let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData
   let certificate = SecCertificateCreateWithData(nil, certificateData!)
   let certificates :[SecCertificate] = [certificate!]
   
   let policies: [String: ServerTrustPolicy] = [
       "域名" : .pinCertificates(certificates: certificates, validateCertificateChain: true, validateHost: true)
   ]
   let manager = Alamofire.SessionManager(configuration: configuration,serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies))
   return manager
}
//把defaultAlamofireManager當引數傳進去就行了
let kProvider = MoyaProvider<APIManager>(endpointClosure: myEndpointClosure, requestClosure: requestClosure, manager:defaultAlamofireManager(), plugins: [networkPlugin], trackInflights: false)
複製程式碼

相關文章