2017-01-19 72 views
0

我一直試圖使用NSURLSession來信任一個證書,因爲從macOS 10.11開始已棄用NSURLConnection變體。我試圖在基於WebKit的應用程序中實現NSURLSession,並且在證書被信任後,什麼都不會發生,並且如果我重新加載網頁,則控制檯中會出現相同的錯誤,表示證書不受信任。使用NSURLSession信任無效證書

我的代碼如下:

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[defaults objectForKey:@"lastSession"]]]; 

NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration]; 
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:self delegateQueue:[NSOperationQueue mainQueue]]; 

NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 

    NSLog(@"Success"); 
}]; 

[dataTask resume]; 

下面是我對didReceiveChallenge方法:

- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler { 
    NSLog(@"Received auth challenge"); 
    if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { 
     NSURL *baseURL = [NSURL URLWithString:[defaults objectForKey:@"lastSession"]]; 
     if([challenge.protectionSpace.host isEqualToString:baseURL.host]) { 
      NSLog(@"Trusting connection to host %@", challenge.protectionSpace.host); 
      NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; 
      [challenge.sender useCredential:credential forAuthenticationChallenge:challenge]; 
      completionHandler(NSURLSessionAuthChallengeUseCredential, credential); 
      NSLog(@"Trusted webpage successfully"); 
     } 
    } 
} 

有我丟失的東西嗎?一些幫助肯定會被讚賞...

回答

0

當你使用NSURLSession時,你不應該在challenge.sender上調用任何東西。只需調用完成處理程序。但是,您也不應該從請求中獲取證書,因爲當您這樣做時基本上完全關閉了該主機名的所有保護。

相反,您應該在您的應用中對錨定證書進行硬編碼並將其添加到受信任的錨點列表中。然後,使用該錨定證書籤署您的服務器證書,並且您的應用將從此開始信任該服務器。

欲瞭解詳情,請閱讀https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/NetworkingTopics/Articles/OverridingSSLChainValidationCorrectly.html