您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 教學 >> iOS 相關教學

iOS 9 ATS 限制下如何繼續使用 HTTP 介面,以及 HTTPS 請求的實作要點

編輯:iOS 相關教學

從 iOS 9 開始,App Transport Security(ATS)默認生效,所有明文 HTTP 請求都會被系統直接攔截。對於有大量歷史介面仍是 HTTP 的項目,這是一個必須正面處理的升級問題。

一、臨時放行方案:修改 Info.plist

如果暫時無法把後端全部遷移到 HTTPS,可以在 Info.plist 中加入以下配置關閉 ATS 檢查:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

需要明確的是,這相當於全局關閉了傳輸安全保護,僅適合過渡期使用。上線前應盡量把介面遷移到 HTTPS,或者改用針對特定域名的白名單配置(NSExceptionDomains),把風險控制在最小範圍。

二、HTTP 與 HTTPS 請求的實現差異

在具體代碼層面,兩者的請求構造幾乎一致,關鍵差異在於 HTTPS 需要處理證書信任的問題。

普通同步請求

NSString *urlString = [NSString stringWithFormat:@"https://127.0.0.1/default.aspx?USER=%@", @"111"];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"GET"];

NSHTTPURLResponse *urlResponse = nil;
NSError *error = [[NSError alloc] init];

NSData *responseData = [NSURLConnection sendSynchronousRequest:request
                                            returningResponse:&urlResponse
                                                        error:&error];

NSMutableString *result = [[NSMutableString alloc] initWithData:responseData
                                                      encoding:NSUTF8StringEncoding];
NSLog(@"The result string is :%@", result);

注意 returningResponse: 需要傳遞地址 &urlResponse,原樣寫成變量名是無法拿到響應對象的。

異步請求與忽略證書校驗

當服務端採用單向 HTTPS 驗證、而 iOS 客戶端需要跳過證書信任檢查時,實現如下:

{
    NSString *urlString = [NSString stringWithFormat:@"https://127.0.0.1/default.aspx?USER=%@", @"111"];

    NSMutableURLRequest *request =
        [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]
                                     cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                 timeoutInterval:5];

    // 設置請求方式為 GET
    [request setHTTPMethod:@"GET"];

    // 添加 Content-Type 頭
    [request addValue:@"text/html" forHTTPHeaderField:@"Content-Type"];

    // 發送請求
    finished = false;
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    // 阻塞當前線程,等待請求結束
    while (!finished)
    {
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
                                 beforeDate:[NSDate distantFuture]];
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    finished = true;
    [connection release];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    finished = true;
}

- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection
{
    return NO;
}

// 以下兩個方法是重點:讓 iOS 客戶端接受服務端的證書
- (BOOL)connection:(NSURLConnection *)connection
canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
    return [protectionSpace.authenticationMethod
            isEqualToString:NSURLAuthenticationMethodServerTrust];
}

- (void)connection:(NSURLConnection *)connection
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    NSLog(@"didReceiveAuthenticationChallenge %@ %zd",
          [[challenge protectionSpace] authenticationMethod],
          (ssize_t)[challenge previousFailureCount]);

    if ([[challenge protectionSpace] authenticationMethod]
            isEqualToString:NSURLAuthenticationMethodServerTrust)
    {
        [[challenge sender] useCredential:[NSURLCredential
                                           credentialForTrust:challenge.protectionSpace.serverTrust]
                   forAuthenticationChallenge:challenge];
        [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
    }
}

// 處理接收到的數據
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
}

三、幾點實踐建議

  • 別忘了置位結束標誌:異步回調裡如果不把 finished 設為 YES,阻塞等待的 while 循環永遠不會退出,主線程會被卡死。
  • 跳過證書校驗僅限測試:關閉證書驗證等於放棄了中間人攻擊的防護,只應出現在開發調試階段,正式環境必須啟用完整校驗。
  • 優先考慮新 API:NSURLConnection 已被標記為過時,新項目建議直接使用 NSURLSession,並配合 ATS 的域名白名單做精細配置。
  • 同步請求不要在主線程用:sendSynchronousRequest: 會阻塞當前線程,放在主線程會直接凍結界面。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved