WKWebView 允許 native 介入到 HTTP 的驗證流程,類似于 URLSession 一樣對 Challenge 進行校驗,具體代碼如下
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler
{
if (![challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { // 非服務端校驗流程,走默認
completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
return;
}
SecTrustResultType result;
int err = SecTrustEvaluate(challenge.protectionSpace.serverTrust, &result); // 用系統證書進行服務端證書校驗
if (err) {
// 證書校驗失敗
completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
return;
}
if (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed) {
// 校驗通過
// kSecTrustResultProceed:驗證成功,且該驗證得到了用戶認可(例如在彈出的是否信任的alert框中選擇always trust)
// kSecTrustResultUnspecified:驗證成功,此證書也被暗中信任了,但是用戶并沒有顯示地決定信任該證書
NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:challenge.protectionSpace.serverTrust];
completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
return;
} else {
// 證書校驗失敗
completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
return;
}
}
參考鏈接