準備
iOS作https適配時對服務器是有必定要求的,服務端必需要是一個符合ATS(App Transport Security)要求的HTTPS。簡單說要知足如下幾個要求:
1.Transport Layer Security協議版本要求TLS1.2以上
2.服務的Ciphers配置要求支持Forward Secrecy等
3.證書籤名算法符合ATS要求等
Moya對應版本
Moya版本號(10.0.x);Alamofire版本號:4.7.x
實現方法
一、默認非HTTPS實現方法:
默認狀況下定義Manager:
MoyaProvider<MultiTarget>.defaultAlamofireManager()
該方法不須要作任何處理,Moya默認已經實現
二、HTTPS免證書實現方法(校驗證書,能夠抓包):
代碼:
let manager: Manager = MoyaProvider<MultiTarget>.defaultAlamofireManager()
manager.delegate.sessionDidReceiveChallenge = {
session,challenge in
return (URLSession.AuthChallengeDisposition.useCredential,URLCredential(trust:challenge.protectionSpace.serverTrust!))
}
注:須要導入:import Alamofire
三、HTTPS+證書實現方法(校驗證書,不能夠抓包)
在實現本方法前,首先須要服務器端提供「*.crt」證書,而後進入證書所在的路徑,控制檯執行如下命令:
openssl x509 -in *.crt -out *.cer -outform der
獲得cer類型證書後,雙擊,導入電腦(有可能不須要導入電腦)。
把轉換好的cer文件拖動到工程中。
上代碼:
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = Manager.defaultHTTPHeaders
let path: String = Bundle.main.path(forResource: "xxx", ofType: "cer") ?? ""
let certificationData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData
let certificate = SecCertificateCreateWithData(nil, certificationData!)
let certificates: [SecCertificate] = [certificate!]
let policies: [String: ServerTrustPolicy] = ["domain": ServerTrustPolicy.pinCertificates(certificates: certificates, validateCertificateChain: true, validateHost: true)]
let manager = Manager(configuration: configuration, serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies))
最後把manager當參數傳遞給MoyaProvider
例如:
MoyaProvider<MultiTarget>(endpointClosure: endpoint,
requestClosure: requestEndpoint,
stubClosure: stubClosure,
manager: manager,
plugins: plugins)