iOS 開發 支援 HTTPS 請求以及 SSL 憑證配置詳解
前言:
眾所周知,Apple 曾宣布從 2017 年開始會逐步要求使用 HTTPS。以下就分享我近日把 HTTP 轉為 HTTPS 的經驗,給還沒動手的朋友參考。
一、憑證準備
1、憑證轉換
在伺服器人員給你 crt 憑證後,進入憑證路徑執行:
// openssl x509 -in 你的憑證.crt -out 你的憑證.cer -outform der
這樣就能得到 cer 類型的憑證,雙擊匯入電腦即可。
2、把憑證放入專案
1、可直接把轉換好的 cer 檔拖進專案。
2、也可在鑰匙串中找到匯入的憑證,右鍵導出,即可獲得 .cer 檔。
二、程式碼準備
<key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> </dict>
1.1 NSURLConnection 設定支援 HTTPS
在 2015 年 iOS 9 更新中,NSURLConnection 被廢棄、由 NSURLSession 取代,因此不建議繼續用這個類別(AFNetworking 2.x 同理)。但考慮到一些舊專案無法立即替換,還是需要說明做法。
程式碼如下:
- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{ if(challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) { // 告訴服務器,客戶端信任證書 // 創建憑據對象 NSURLCredential *credntial = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; // 告訴服務器信任證書 [challenge.sender useCredential:credntial forAuthenticationChallenge:challenge]; } }
只要加上這個代理方法,就能在不影響原有請求的基礎上,增加 HTTPS 支援。
1.2 NSURLSession 設定支援 HTTPS
現在推薦用 NSURLSession 處理網路請求,使用系統自帶類別可參考:
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * __nullable credential))completionHandler { // 判斷是否是信任服務器證書 if(challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) { // 告訴服務器,客戶端信任證書 // 創建憑據對象 NSURLCredential *credntial = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; // 通過completionHandler告訴服務器信任證書 completionHandler(NSURLSessionAuthChallengeUseCredential,credntial); } NSLog(@"protectionSpace = %@",challenge.protectionSpace); }
2. 使用 AFNetworking 發送網路請求
AFNetworking 是廣受歡迎的網路庫,架構良好、API 豐富、模組化,使用起來非常輕鬆。
2.1 AFNetworking 2.x 版本
此版本可用 AFHTTPRequestOperationManager 處理請求,做法是給它設定一些參數以支援 HTTPS。
支援 HTTPS(校驗憑證,不可抓包):
// 1.初始化單例類 AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager]; mgr.securityPolicy.SSLPinningMode = AFSSLPinningModeCertificate; // 2.設置證書模式 NSString * cerPath = [[NSBundle mainBundle] pathForResource:@"xxx" ofType:@"cer"]; NSData * cerData = [NSData dataWithContentsOfFile:cerPath]; mgr.securityPolicy.pinnedCertificates = [[NSArray alloc] initWithObjects:cerData, nil]; // 客戶端是否信任非法證書 mgr.securityPolicy.allowInvalidCertificates = YES; // 是否在證書域字段中驗證域名 [mgr.securityPolicy setValidatesDomainName:NO];
支援 HTTPS(不校驗憑證,可抓包查看):
// 1.初始化單例類 AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager]; mgr.securityPolicy.SSLPinningMode = AFSSLPinningModeCertificate; // 2.設置非校驗證書模式 mgr.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; mgr.securityPolicy.allowInvalidCertificates = YES; [mgr.securityPolicy setValidatesDomainName:NO];
2.2 AFNetworking 3.x 版本
Xcode 7.0 之後 Apple 廢棄了 NSURLConnection,AFN 3.0 也隨之改用基於 NSURLSession 封裝的 AFHTTPSessionManager,取代了 AFHTTPRequestOperationManager。
支援 HTTPS(校驗憑證,不可抓包):
// 1.初始化 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; manager.securityPolicy.SSLPinningMode = AFSSLPinningModeCertificate; // 2.設置證書模式 NSString * cerPath = [[NSBundle mainBundle] pathForResource:@"xxx" ofType:@"cer"]; NSData * cerData = [NSData dataWithContentsOfFile:cerPath]; manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate withPinnedCertificates:[[NSSet alloc] initWithObjects:cerData, nil]]; // 客戶端是否信任非法證書 mgr.securityPolicy.allowInvalidCertificates = YES; // 是否在證書域字段中驗證域名 [mgr.securityPolicy setValidatesDomainName:NO];
支援 HTTPS(不校驗憑證,可抓包查看):
// 1.初始化 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; // 2.設置非校驗證書模式 manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; manager.securityPolicy.allowInvalidCertificates = YES; [manager.securityPolicy setValidatesDomainName:NO];
到這裡配置就完成了,希望對你有所幫助。