專案裡一直用 NSURLConnection 打 HTTP 介面,最近基於安全性的考量,想把整條請求鏈路改成 HTTPS。改起來其實不難,關鍵在於你的伺服器用的是一般憑證,還是需要 App 端自帶憑證做比對。
這是我們專案採用的一種,步驟非常精簡:
http 改成 https。Security.framework,若沒有就手動加入。前面的動作與情況一完全相同,差別只在於你要額外實作 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 時才交出憑證,其餘一律取消挑戰。這樣就等於在系統信任鏈之外多加了一道自家憑證的門檻。