iOS HTTPS自建證書驗證

前言

公司項目由HTTP轉為HTTPS,需要對網絡請求進行自建證書驗證。主要是AFNetWorkingSDWebImageWKWebView

HTTP與HTTPS

詳情參考iOS開發-網絡、Http與Https

AFNetWorking

詳情參考AFNetworking之于https認證。之后的主要是使用AFNetWorking的方法進行驗證。

  • 自建證書驗證工具方法
static AFSecurityPolicy *securityPolicyShare = NULL;
@implementation HTTPSAuthenticationChallenge

+(AFSecurityPolicy *)customSecurityPolicy {
    // 保證證書驗證初始化一次
    if (securityPolicyShare != NULL) {
        return securityPolicyShare;
    }

    // 加載證書
    NSString *crtBundlePath = [[NSBundle mainBundle] pathForResource:@"Res" ofType:@"bundle"];
    NSBundle *resBundle = [NSBundle bundleWithPath:crtBundlePath];
    NSSet<NSData *> *cerDataSet = [AFSecurityPolicy certificatesInBundle:resBundle];
    
    // AFSSLPinningModeCertificate使用證書驗證模式
    securityPolicyShare = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate withPinnedCertificates:cerDataSet];
    
    return securityPolicyShare;
    
}

+ (void)authenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler {
    // 獲取服務器證書信息
    SecTrustRef serverTrust = [[challenge protectionSpace] serverTrust];
    
    NSURLCredential *credential = nil;
    NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
    
    // 基于客戶端的安全策略來決定是否信任該服務器,不信任的話,也就沒必要響應驗證
    if ([[HTTPSAuthenticationChallenge customSecurityPolicy] evaluateServerTrust:serverTrust forDomain:nil]) {
        
        // 創建挑戰證書(注:挑戰方式為UseCredential和PerformDefaultHandling都需要新建證書)
        credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
        
        // credential存在時使用證書驗證
        // credential為nil時忽略證書,默認的處理方式
        disposition = credential == nil ?  NSURLSessionAuthChallengePerformDefaultHandling : NSURLSessionAuthChallengeUseCredential;
        
    } else {
        // 忽略證書,取消請求
        disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
    }
    
    
    if (completionHandler) {
        completionHandler(disposition,credential);
    }
}

@end

SDWebImage

  • 創建SDWebImageDownloader的分類,在分類中進行驗證

SDWebImageDownloaderSDWebImageView下載圖片的核心類,在分類中重寫NSURLSession的代理方法didReceiveChallenge進行自建證書的驗證

- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge

 completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler {
    
    [HTTPSAuthenticationChallenge authenticationChallenge:challenge completionHandler:completionHandler];
    
}

WKWebView

  • WKWebView的驗證常規情況下在navigationDelegatedidReceiveAuthenticationChallenge中進行
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler{
   [HTTPSAuthenticationChallenge authenticationChallenge:challenge completionHandler:completionHandler];
}
  • 非常規情況,假如WKWebView展示html里有大量圖片,并且用戶點擊圖片時進行展示。

    1. 不考慮效率
      這種情況下可以在WKWebView加載完成后使用JS注入的方式獲取html里圖片的src,然后利用SDWebImage進行預下載。這樣就會造成圖片兩次下載(網頁加載時下載圖片和用戶點擊展示圖片時進行下載),浪費流量。但此方法可以讓我們正常的在navigationDelegatedidReceiveAuthenticationChallenge中進行證書驗證。
    - (void)imagesPrefetcher:(WKWebView *)webView {
      static  NSString * const jsGetImages =
      @"function getImages(){\
      var objs = document.getElementsByTagName(\"img\");\
      var imgScr = '';\
      for(var i=0;i<objs.length;i++){\
      imgScr = imgScr + objs[i].src + '+';\
      };\
      return imgScr;\
      };";
      
      [webView evaluateJavaScript:jsGetImages completionHandler:nil];
      [webView evaluateJavaScript:@"getImages()" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
          
          NSArray *urlArray = [NSMutableArray arrayWithArray:[result componentsSeparatedByString:@"+"]];
          //urlResurlt 就是獲取到得所有圖片的url的拼接;mUrlArray就是所有Url的數組
          CGLog(@"Image--%@",urlArray);
          NSMutableArray<NSURL *> *tempURLs = [NSMutableArray array];
          for (NSString* urlStr in urlArray) {
              NSURL *url = [NSURL URLWithString:urlStr];
              if (url) {
                  [tempURLs addObject:url];
              }
          }
          [[SDWebImagePrefetcher sharedImagePrefetcher] prefetchURLs:tempURLs];
      }];
    }
    
    1. 考慮效率
      使用NSURLProtocol進行攔截html加載圖片的請求,由自己來進行請求并緩存圖片,這樣可以避免在用點擊時展示圖片時再次請求,直接使用緩存圖片進行展示就行了。雖然節省了流量,提高了效率,但是我們不能夠navigationDelegatedidReceiveAuthenticationChallenge中進行證書驗證了,這個代理方法不會走的,我們要考慮在NSURLProtocol中進行驗證。
    /** WhiteList validation */
      @interface NSURLRequest (WhiteList)
      - (BOOL)isInWhiteList;
      - (BOOL)is4CGTNPictureResource;
      - (BOOL)is4CGTNResource;
      @end
    
      @implementation NSURLRequest (WhiteList)
    
      - (BOOL)isInWhiteList {
          // 手機端非CGTN的第三方不需要驗證,也是屬于白名單的
          BOOL isMobileRequest = [self.URL.host isEqualToString:@"events.appsflyer.com"]
          || [self.URL.host isEqualToString:@"ssl.google-analytics.com"];
          if (isMobileRequest) {
              return YES;
          }
          
          // webView
          NSArray<NSString *> *whiteListStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"kWhiteList"];
          if (whiteListStr.count == 0) {
              return YES;
          }
          
          NSSet *whiteListSet = [NSSet setWithArray:whiteListStr];
          // requestURL --- scheme + host
          NSString *requestURL = [[self.URL.scheme stringByAppendingString:@"://"] stringByAppendingString:self.URL.host];
          
          BOOL isInList = [whiteListSet containsObject:requestURL];
          // 在白名單的使用系統默認處理
          // 不在白名單的進行攔截驗證
          return isInList;
      }
    
      - (BOOL)is4CGTNResource {
          NSURLComponents *components = [[NSURLComponents alloc] initWithURL:self.URL resolvingAgainstBaseURL:YES];
          
          BOOL isCGTNResource = [components.host containsString:@"cgtn.com"];
          if (isCGTNResource) {
              return YES;
          }
          
          return NO;
      }
    
      - (BOOL)is4CGTNPictureResource {
          NSURLComponents *components = [[NSURLComponents alloc] initWithURL:self.URL resolvingAgainstBaseURL:YES];
          
          BOOL isCGTNResource = [components.host containsString:@"cgtn.com"];
          NSString *extensionName = self.URL.pathExtension;
          BOOL canHandle = [extensionName containsString:@"png"] || [extensionName containsString:@"jpg"] || [extensionName containsString:@"jpeg"] || [extensionName containsString:@"gif"];
          if (canHandle && isCGTNResource) {
              return YES;
          }
          
          return NO;
      }
    
      @end
    
    
      static NSString *const handledKey = @"com.cgtn.www";
    
      @interface CGTNURLProtocol ()<NSURLSessionDelegate>
      /** 用于圖片鏈接交由SDWebImage 管理 */
      @property (strong, nonatomic) id<SDWebImageOperation> operation;
      /** 其他非圖片任務交由 Cache 管理, task任務 */
      @property (strong, nonatomic) NSURLSessionDataTask *dataTask;
      /** 是否為圖片鏈接 */
      @property (nonatomic) BOOL isPicture;
    
      @end
    
      @implementation CGTNURLProtocol
    
      + (BOOL)canInitWithRequest:(NSURLRequest *)request {
          if (!request.URL || [self propertyForKey:handledKey inRequest:request]) {
              return NO;
          }
    
          CGLog(@"canInitWithRequest----%@",request.URL);
          
          // 白名單中的鏈接不進行攔截. 默認外部處理
          // CGTN 的資源強制進行驗證
          return !request.isInWhiteList || request.is4CGTNResource;
      }
    
      + (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
          return request;
      }
    
      + (BOOL)requestIsCacheEquivalent:(NSURLRequest *)a toRequest:(NSURLRequest *)b {
          return [super requestIsCacheEquivalent:a toRequest:b];
      }
    
      - (void)startLoading {
          [self.class setProperty:@(YES) forKey:handledKey inRequest:self.request.mutableCopy];
          
          // 攔截到的請求必須為 HTTPS
          if ([self.request.URL.scheme isEqualToString:@"http"]) {
              NSError *error = [NSError CGTNErrorWithCode:NSURLErrorAppTransportSecurityRequiresSecureConnection
                                              description:@"Deny HTTP request"];
              [self.client URLProtocol:self didFailWithError:error];
              return;
          }
          
          self.isPicture = self.request.is4CGTNPictureResource;
          
          if (self.isPicture) {
              __weak typeof(self) weakSelf = self;
              self.operation = [SDWebImageManager.sharedManager loadImageWithURL:self.request.URL
                                 options:SDWebImageRetryFailed progress:nil
                           completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
                               if (error) {
                                   [weakSelf.client URLProtocol:weakSelf didFailWithError:error];
                                   return;
                               }
                               NSData *imageData = data;
                               if (!data && image) {
                                   imageData = image.sd_imageData;
                               }
                               if (!imageData) {
                                   [weakSelf.client URLProtocolDidFinishLoading:weakSelf];
                                   return;
                               }
                               
                               NSURLResponse *response = [[NSURLResponse alloc] initWithURL:imageURL
                                                                                   MIMEType:nil
                                                                      expectedContentLength:imageData.length
                                                                           textEncodingName:nil];
                               [weakSelf.client URLProtocol:self didReceiveResponse:response
                                         cacheStoragePolicy:NSURLCacheStorageAllowed];
                               [weakSelf.client URLProtocol:weakSelf didLoadData:imageData];
                               [weakSelf.client URLProtocolDidFinishLoading:weakSelf];
                           }];
              return;
          }
          
          // 非圖片請求
          NSURLSessionConfiguration *config = NSURLSessionConfiguration.defaultSessionConfiguration;
          NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
          self.dataTask = [session dataTaskWithRequest:self.request];
          
          [self.dataTask resume];
      }
    
      - (void)stopLoading {
          if (self.isPicture) {
              [self.operation cancel];
              return;
          }
    
          [self.dataTask cancel];
      }
    
      #pragma mark - NSURLSessionDelegate
      - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
          if (error) {
              [self.client URLProtocol:self didFailWithError:error];
          } else {
              [self.client URLProtocolDidFinishLoading:self];
          }
      }
    
      - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
          [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
          
          completionHandler(NSURLSessionResponseAllow);
      }
    
      - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
          [self.client URLProtocol:self didLoadData:data];
      }
    
      - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask willCacheResponse:(NSCachedURLResponse *)proposedResponse completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler
      {
          completionHandler(proposedResponse);
      }
    
      - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler {
          
          [HTTPSAuthenticationChallenge authenticationChallenge:challenge completionHandler:completionHandler];
      }
      @end
    
    
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,030評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,310評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,951評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,796評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,566評論 6 407
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,055評論 1 322
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,142評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,303評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,799評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,683評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,899評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,409評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,135評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,520評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,757評論 1 282
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,528評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,844評論 2 372