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

nginx 與 iOS 實作 HTTPS 雙向認證完整教學

編輯:iOS 開發綜合

普通的 HTTPS 只驗證伺服器身分:客戶端檢查伺服器憑證是否可信。但在某些高安全場景——企業內部 API、金融交易、裝置對裝置通訊——我們還需要反向驗證:伺服器也要確認「你是誰」。這就是雙向認證(mutual TLS,又稱 client certificate)。本文示範如何用 nginx 建立服務端,並在 iOS 客戶端完成憑證出示。

一、服務端:nginx 設定

關鍵設定如下:

listen 443;
server_name localhost;

ssl on;
ssl_certificate         /usr/local/opt/nginx/certificates/server.cer;
ssl_certificate_key     /usr/local/opt/nginx/certificates/server.key.pem;
ssl_client_certificate  /usr/local/opt/nginx/certificates/ca.cer;
ssl_verify_client       on;

逐行說明:

  • ssl on:啟用 HTTPS
  • ssl_certificate:伺服器憑證的路徑
  • ssl_certificate_key:伺服器私鑰的路徑
  • ssl_verify_client on:開啟客戶端憑證驗證,這就是雙向認證的鑰匙
  • ssl_client_certificate:用來簽發客戶端憑證的根憑證(CA)

為什麼是根憑證?因為一張根憑證可以簽發大量客戶端憑證,只要對方出示的憑證是由這張 CA 簽發且未過期、未撤銷,nginx 就視為通過。這樣一來,新增裝置只需再簽一張憑證,不必改動伺服器設定。

設定完成後,通常還要把 80 端口的 HTTP 請求全部導向 443。否則使用者仍可用明文 HTTP 存取,安全防護形同虛設:

server {
    listen 80;
    server_name localhost;
    return 301 https://$host$request_uri;
}

二、iOS 客戶端:以 NSURLSession 出示憑證

網路上關於 iOS client certificate 的討論,很多仍在使用 NSURLConnection 與已淘汰的 delegate 方法。以下改用現代的 NSURLSession 寫法。

步驟一:建立工作階段並發出請求

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration
                                                      delegate:self
                                                 delegateQueue:nil];

NSURL *url = [NSURL URLWithString:@"https://localhost/svc/portal/setting"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:@"GET"];

NSURLSessionDataTask *task =
    [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSString *message = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@", message);
    }];
[task resume];

步驟二:在驗證回呼中判斷階段並回應

在 SSL 握手階段,系統會呼叫下列 delegate 方法兩次:第一次是 iOS 驗證伺服器,第二次是伺服器驗證 iOS。

- (void)URLSession:(NSURLSession *)session
    didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
      completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition,
                                  NSURLCredential *credential))completionHandler
{
    NSString *method = challenge.protectionSpace.authenticationMethod;
    NSLog(@"%@", method);

    // 第一階段:驗證伺服器憑證
    if ([method isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        NSString *host = challenge.protectionSpace.host;
        NSLog(@"%@", host);

        NSURLCredential *credential =
            [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
        completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
        return;
    }

    // 第二階段:出示客戶端憑證(client certificate)
    NSString *thePath = [[NSBundle mainBundle] pathForResource:@"client" ofType:@"p12"];
    NSData *PKCS12Data = [[NSData alloc] initWithContentsOfFile:thePath];
    CFDataRef inPKCS12Data = (CFDataRef)CFBridgingRetain(PKCS12Data);

    SecIdentityRef identity = NULL;
    OSStatus result = [self extractP12Data:inPKCS12Data toIdentity:&identity];

    if (result != errSecSuccess) {
        completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
        return;
    }

    SecCertificateRef certificate = NULL;
    SecIdentityCopyCertificate(identity, &certificate);

    const void *certs[] = { certificate };
    CFArrayRef certArray = CFArrayCreate(kCFAllocatorDefault, certs, 1, NULL);

    NSURLCredential *credential =
        [NSURLCredential credentialWithIdentity:identity
                                    certificates:(NSArray *)CFBridgingRelease(certArray)
                                     persistence:NSURLCredentialPersistencePermanent];

    completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
}

// 從 p12 檔案取出 SecIdentity
- (OSStatus)extractP12Data:(CFDataRef)inP12Data toIdentity:(SecIdentityRef *)identity
{
    OSStatus securityError = errSecSuccess;

    CFStringRef password = CFSTR("你的p12密碼");
    const void *keys[]   = { kSecImportExportPassphrase };
    const void *values[] = { password };

    CFDictionaryRef options = CFDictionaryCreate(NULL, keys, values, 1, NULL, NULL);
    CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);

    securityError = SecPKCS12Import(inP12Data, options, &items);

    if (securityError == 0) {
        CFDictionaryRef ident = CFArrayGetValueAtIndex(items, 0);
        const void *tempIdentity = CFDictionaryGetValue(ident, kSecImportItemIdentity);
        *identity = (SecIdentityRef)tempIdentity;
    }

    if (options) {
        CFRelease(options);
    }
    return securityError;
}

三、最常見的失敗原因

沒有呼叫 completionHandler。這是最大的陷阱。新版的 NSURLSession 挑戰回呼必須呼叫 completionHandler 來告知系統你的決定;網路上大量教學仍在示範舊寫法:

[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];

這行程式碼在 NSURLSession 的 delegate 中完全無效——它屬於已淘汰的 NSURLConnection 介面。少了 completionHandler,連線會永久卡住直到逾時。

p12 密碼或憑證鏈有誤。SecPKCS12Import 回傳非 0 就代表匯入失敗,常見原因是密碼錯誤或 p12 檔本身格式不符。請檢查 securityError 的實際值。

伺服器憑證未受信任。若 iOS 不信任伺服器憑證,第一階段的 credentialForTrust: 仍會被接受,但後續連線會失敗。測試環境可暫時放寬,正式環境務必部署由公共 CA 簽發的憑證。

忘記清理 C 記憶體。CFBridgingRetain 轉出的 CF 物件不受 ARC 管理,若無對應的 CFRelease 或 CFBridgingRelease 就會洩漏。範例中 certArray 用了 CFBridgingRelease 交給 ARC,options 則手動 CFRelease,這兩種風格不可混用同一個物件。

憑證過期與撤銷。雙向認證的運維成本主要在憑證生命週期管理。實務上應建立憑證簽發、發放、輪替與撤銷(CRL/OCSP)的流程,並在 App 中處理憑證失效時的錯誤提示。

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