iOS HTTPS自建證書驗證

前言

公司項目由HTTP轉(zhuǎn)為HTTPS椰于,需要對網(wǎng)絡(luò)請求進行自建證書驗證俐巴。主要是AFNetWorking综芥、SDWebImageWKWebView泰演。

HTTP與HTTPS

詳情參考iOS開發(fā)-網(wǎng)絡(luò)、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 {
    // 獲取服務(wù)器證書信息
    SecTrustRef serverTrust = [[challenge protectionSpace] serverTrust];
    
    NSURLCredential *credential = nil;
    NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
    
    // 基于客戶端的安全策略來決定是否信任該服務(wù)器,不信任的話护糖,也就沒必要響應(yīng)驗證
    if ([[HTTPSAuthenticationChallenge customSecurityPolicy] evaluateServerTrust:serverTrust forDomain:nil]) {
        
        // 創(chuàng)建挑戰(zhàn)證書(注:挑戰(zhàn)方式為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

  • 創(chuàng)建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的驗證常規(guī)情況下在navigationDelegatedidReceiveAuthenticationChallenge中進行
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler{
   [HTTPSAuthenticationChallenge authenticationChallenge:challenge completionHandler:completionHandler];
}
  • 非常規(guī)情況锰扶,假如WKWebView展示html里有大量圖片献酗,并且用戶點擊圖片時進行展示。

    1. 不考慮效率
      這種情況下可以在WKWebView加載完成后使用JS注入的方式獲取html里圖片的src,然后利用SDWebImage進行預(yù)下載坷牛。這樣就會造成圖片兩次下載(網(wǎng)頁加載時下載圖片和用戶點擊展示圖片時進行下載)罕偎,浪費流量。但此方法可以讓我們正常的在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的數(shù)組
          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加載圖片的請求,由自己來進行請求并緩存圖片忙干,這樣可以避免在用點擊時展示圖片時再次請求器予,直接使用緩存圖片進行展示就行了。雖然節(jié)省了流量捐迫,提高了效率乾翔,但是我們不能夠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];
          // 在白名單的使用系統(tǒng)默認處理
          // 不在白名單的進行攔截驗證
          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;
      /** 其他非圖片任務(wù)交由 Cache 管理, task任務(wù) */
      @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
    
    
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末赞哗,一起剝皮案震驚了整個濱河市雷则,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌肪笋,老刑警劉巖月劈,帶你破解...
    沈念sama閱讀 216,651評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異藤乙,居然都是意外死亡猜揪,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,468評論 3 392
  • 文/潘曉璐 我一進店門坛梁,熙熙樓的掌柜王于貴愁眉苦臉地迎上來而姐,“玉大人,你說我怎么就攤上這事划咐∷┠睿” “怎么了?”我有些...
    開封第一講書人閱讀 162,931評論 0 353
  • 文/不壞的土叔 我叫張陵褐缠,是天一觀的道長政鼠。 經(jīng)常有香客問我,道長送丰,這世上最難降的妖魔是什么缔俄? 我笑而不...
    開封第一講書人閱讀 58,218評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮器躏,結(jié)果婚禮上俐载,老公的妹妹穿的比我還像新娘。我一直安慰自己登失,他們只是感情好遏佣,可當(dāng)我...
    茶點故事閱讀 67,234評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著揽浙,像睡著了一般状婶。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上馅巷,一...
    開封第一講書人閱讀 51,198評論 1 299
  • 那天膛虫,我揣著相機與錄音,去河邊找鬼钓猬。 笑死稍刀,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的敞曹。 我是一名探鬼主播账月,決...
    沈念sama閱讀 40,084評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼澳迫!你這毒婦竟也來了局齿?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,926評論 0 274
  • 序言:老撾萬榮一對情侶失蹤橄登,失蹤者是張志新(化名)和其女友劉穎抓歼,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體拢锹,經(jīng)...
    沈念sama閱讀 45,341評論 1 311
  • 正文 獨居荒郊野嶺守林人離奇死亡谣妻,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,563評論 2 333
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了面褐。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片拌禾。...
    茶點故事閱讀 39,731評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖展哭,靈堂內(nèi)的尸體忽然破棺而出湃窍,到底是詐尸還是另有隱情,我是刑警寧澤匪傍,帶...
    沈念sama閱讀 35,430評論 5 343
  • 正文 年R本政府宣布您市,位于F島的核電站,受9級特大地震影響役衡,放射性物質(zhì)發(fā)生泄漏茵休。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,036評論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望榕莺。 院中可真熱鬧俐芯,春花似錦、人聲如沸钉鸯。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,676評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽唠雕。三九已至贸营,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間岩睁,已是汗流浹背钞脂。 一陣腳步聲響...
    開封第一講書人閱讀 32,829評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留捕儒,地道東北人冰啃。 一個月前我還...
    沈念sama閱讀 47,743評論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像肋层,于是被迫代替她去往敵國和親亿笤。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,629評論 2 354