您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

把 NSURLConnection 的請求從 HTTP 換成 HTTPS 的兩種做法

編輯:iOS 開發綜合

專案裡一直用 NSURLConnection 打 HTTP 介面,最近基於安全性的考量,想把整條請求鏈路改成 HTTPS。改起來其實不難,關鍵在於你的伺服器用的是一般憑證,還是需要 App 端自帶憑證做比對。

情況一:不需要憑證驗證

這是我們專案採用的一種,步驟非常精簡:

  1. 直接把介面網址中的 http 改成 https。
  2. 確認專案已經連結 Security.framework,若沒有就手動加入。
  3. 完成,可以直接發請求了。

情況二:需要憑證驗證

前面的動作與情況一完全相同,差別只在於你要額外實作 NSURLConnection 的認證挑戰回呼方法,攔下伺服器送來的 challenge 並自行比對憑證:

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    static CFArrayRef certs;
    if (!certs) {
        NSData *certData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"srca" ofType:@"cer"]];
        SecCertificateRef rootcert = SecCertificateCreateWithData(kCFAllocatorDefault, CFBridgingRetain(certData));
        const void *array[1] = { rootcert };
        certs = CFArrayCreate(NULL, array, 1, &kCFTypeArrayCallBacks);
        CFRelease(rootcert); // 這裡釋放只是為了整齊,實際影響不大
    }
    SecTrustRef trust = [[challenge protectionSpace] serverTrust];
    int err;
    SecTrustResultType trustResult = 0;
    err = SecTrustSetAnchorCertificates(trust, certs);
    if (err == noErr) {
        err = SecTrustEvaluate(trust, &trustResult);
    }
    CFRelease(trust);
    BOOL trusted = (err == noErr) && ((trustResult == kSecTrustResultProceed) || (trustResult == kSecTrustResultConfirm) || (trustResult == kSecTrustResultUnspecified));
    if (trusted) {
        [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]
             forAuthenticationChallenge:challenge];
    } else {
        [challenge.sender cancelAuthenticationChallenge:challenge];
    }
}

這段邏輯的重點是:把 App 內打包的 srca.cer 讀成 SecCertificate,組成一條信任錨點陣列,塞給伺服器送來的 trust 物件,再呼叫 SecTrustEvaluate 取得信任結果。只有在結果為 Proceed、Confirm 或 Unspecified 時才交出憑證,其餘一律取消挑戰。這樣就等於在系統信任鏈之外多加了一道自家憑證的門檻。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved