HTTPS 除了「加密」,還能「驗身分」。當伺服器不只要確認用戶端可信任,用戶端也需要出示憑證證明自己是誰時,就進入了雙向認證(Mutual Authentication)的領域。本文示範如何用 NSURLSession 完成這件事。
前置作業包含使用 keytool 產生自簽名憑證,並在 Tomcat 上設定 HTTPS 雙向認證。這部分牽涉到 HTTPS、SSL/TLS 的基本概念與憑證簽章流程,建議先確認伺服器端已經能用瀏覽器(安裝憑證後)正常訪問,再回頭處理 App。
用瀏覽器訪問這類 HTTPS 服務時,需要安裝 mykey.p12(客戶端憑證)與 tomcat.cer(伺服器憑證)兩個檔案。App 端同樣要把它們加進來:

別忘了同時到「專案」→「Build Phases」→「Copy Bundle Resources」把這兩個檔案加入,否則執行期會讀不到。

因為我們用的是自簽名憑證,而蘋果的 ATS(App Transport Security)只信任知名 CA 簽發的憑證,所以即使在 iOS 9 下走 HTTPS 也會被攔截。需要在 Info.plist 加上(iOS 8 不需要):
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
核心在 URLSession(_:didReceiveChallenge:completionHandler:) 這個 delegate 方法:伺服器何時要求認證,它就會被呼叫。我們在其中分辨是「伺服器憑證」還是「客戶端憑證」,各自處理。
import UIKit
import Foundation
class ViewController: UIViewController, NSURLSessionDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// 取得資料
httpGet(NSMutableURLRequest(URL: NSURL(string: "https://192.168.1.101:8443")!))
}
// 使用 NSURLSession 請求資料
func httpGet(request: NSMutableURLRequest!) {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: configuration,
delegate: self, delegateQueue: NSOperationQueue.mainQueue())
let dataTask = session.dataTaskWithRequest(request,
completionHandler: {(data, response, error) -> Void in
if error != nil {
print(error?.code)
print(error?.description)
} else {
let str = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("訪問成功,獲取數據如下:")
print(str)
}
}) as NSURLSessionTask
dataTask.resume() // 記得 resume,否則任務不會啟動
}
// 伺服器要求授權時會呼叫此 delegate 方法
func URLSession(session: NSURLSession,
didReceiveChallenge challenge: NSURLAuthenticationChallenge,
completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
// 認證伺服器憑證
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
print("服務端證書認證!")
let serverTrust: SecTrustRef = challenge.protectionSpace.serverTrust!
let certificate = SecTrustGetCertificateAtIndex(serverTrust, 0)!
let remoteCertificateData = CFBridgingRetain(SecCertificateCopyData(certificate))!
let cerPath = NSBundle.mainBundle().pathForResource("tomcat", ofType: "cer")!
let localCertificateData = NSData(contentsOfFile: cerPath)!
if remoteCertificateData.isEqualToData(localCertificateData) == true {
let credential = NSURLCredential(forTrust: serverTrust)
challenge.sender?.useCredential(credential,
forAuthenticationChallenge: challenge)
completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential,
NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!))
} else {
completionHandler(.CancelAuthenticationChallenge, nil)
}
// 認證客戶端憑證
} else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodClientCertificate {
print("客戶端證書認證!")
let identityAndTrust: IdentityAndTrust = self.extractIdentity()
let urlCredential: NSURLCredential = NSURLCredential(
identity: identityAndTrust.identityRef,
certificates: identityAndTrust.certArray as? [AnyObject],
persistence: NSURLCredentialPersistence.ForSession)
completionHandler(.UseCredential, urlCredential)
// 其他情況一律拒絕
} else {
print("其它情況(不接受認證)")
completionHandler(.CancelAuthenticationChallenge, nil)
}
}
// 從 p12 檔案取出身分與憑證鏈
func extractIdentity() -> IdentityAndTrust {
var identityAndTrust: IdentityAndTrust!
var securityError: OSStatus = errSecSuccess
let path: String = NSBundle.mainBundle().pathForResource("mykey", ofType: "p12")!
let PKCS12Data = NSData(contentsOfFile: path)!
let key: NSString = kSecImportExportPassphrase as NSString
let options: NSDictionary = [key: "123456"] // 客戶端憑證密碼
var items: CFArray?
securityError = SecPKCS12Import(PKCS12Data, options, &items)
if securityError == errSecSuccess {
let certItems: CFArray = items as CFArray!
let certItemsArray: Array = certItems as Array
let dict: AnyObject? = certItemsArray.first
if let certEntry: Dictionary = dict as? Dictionary<String, AnyObject> {
// 取出 identity
let identityPointer: AnyObject? = certEntry["identity"]
let secIdentityRef: SecIdentityRef = identityPointer as! SecIdentityRef!
print("\(identityPointer) :::: \(secIdentityRef)")
// 取出 trust
let trustPointer: AnyObject? = certEntry["trust"]
let trustRef: SecTrustRef = trustPointer as! SecTrustRef
print("\(trustPointer) :::: \(trustRef)")
// 取出憑證鏈
let chainPointer: AnyObject? = certEntry["chain"]
identityAndTrust = IdentityAndTrust(identityRef: secIdentityRef,
trust: trustRef, certArray: chainPointer!)
}
}
return identityAndTrust
}
}
// 存放認證相關資訊的結構
struct IdentityAndTrust {
var identityRef: SecIdentityRef
var trust: SecTrustRef
var certArray: AnyObject
}
主控台輸出如下:

可以。既然用的是自簽名憑證,伺服器的可信度其實是由用戶端自行判斷的,因此專案裡只放 mykey.p12 也能跑。差別在於伺服器認證那段:不再比對憑證內容,而是檢查主機位址是否在我們預先定義的白名單中,是就信任。
class ViewController: UIViewController, NSURLSessionDelegate {
// 自簽名網站白名單
let selfSignedHosts = ["192.168.1.101", "www.hangge.com"]
override func viewDidLoad() {
super.viewDidLoad()
httpGet(NSMutableURLRequest(URL: NSURL(string: "https://192.168.1.101:8443")!))
}
func URLSession(session: NSURLSession,
didReceiveChallenge challenge: NSURLAuthenticationChallenge,
completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
// 伺服器認證:位址在白名單內即可信任
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust
&& self.selfSignedHosts.contains(challenge.protectionSpace.host) {
print("服務器認證!")
let credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!)
completionHandler(.UseCredential, credential)
// 客戶端憑證認證(此段與前例相同)
} else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodClientCertificate {
print("客戶端證書認證!")
let identityAndTrust: IdentityAndTrust = self.extractIdentity()
let urlCredential: NSURLCredential = NSURLCredential(
identity: identityAndTrust.identityRef,
certificates: identityAndTrust.certArray as? [AnyObject],
persistence: NSURLCredentialPersistence.ForSession)
completionHandler(.UseCredential, urlCredential)
} else {
print("其它情況(不接受認證)")
completionHandler(.CancelAuthenticationChallenge, nil)
}
}
// extractIdentity() 實作同前
}
比對憑證與信任白名單這類「自行驗證」的寫法,等於把信任決策交給客戶端,中間人攻擊只要換掉憑證就有可能得逞。因此這套流程只適合內網環境、測試環境或企業自有裝置管理(MDM)情境;對外的正式服務,請務必使用由公共 CA 簽發的憑證,讓系統的預設信任鏈替你驗證,並把憑證密碼放進 Keychain 而非寫死在程式碼裡。