理論上憑證和網域必須一致,可是有時候想在不一致時來連線,遇到被阻擋問題該如何解決呢?
若遇到上圖問題,iOS 會回報錯誤:
Error : Error Domain=NSURLErrorDomain Code=-1202 “The certificate for this server is invalid. You might be connecting to a server that is pretending to be “app.happystudio.io” which could put your confidential information at risk."
亦或是如下:
finished with error [-1202] Error Domain=NSURLErrorDomain Code=-1202 “此伺服器的憑證無效。您所連接的伺服器可能是冒用「ptapp.happystudio.io」的伺服器,並且可能會對您的私密資訊造成風險。" UserInfo={NSLocalizedRecoverySuggestion=您仍然要連接伺服器嗎?, _kCFStreamErrorDomainKey=3, NSErrorPeerCertificateChainKey=(
“<cert(0x1061bc400) s: app.happystudio.io i: R3>",
“<cert(0x106221c00) s: R3 i: ISRG Root X1>",
“<cert(0x10621f200) s: ISRG Root X1 i: DST Root CA X3>"
程式碼可以這麼設定,在 NSURLSession 進行 delegate,強制相信 Server。
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler{
NSLog(@"didReceiveChallenge %@", challenge.protectionSpace);
NSLog(@"調用了最外層");
// 判斷服務器返回的證書類型, 是否是服務器信任
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
NSLog(@"調用了裡面這一層是服務器信任的證書");
/*
NSURLSessionAuthChallengeUseCredential = 0, 使用證書
NSURLSessionAuthChallengePerformDefaultHandling = 1, 忽略證書(默認的處理方式)
NSURLSessionAuthChallengeCancelAuthenticationChallenge = 2, 忽略書證, 並取消這次請求
NSURLSessionAuthChallengeRejectProtectionSpace = 3, 拒絕當前這一次, 下一次再詢問
*/
NSURLCredential *card = [[NSURLCredential alloc] initWithTrust:challenge.protectionSpace.serverTrust];
completionHandler(NSURLSessionAuthChallengeUseCredential, card);
}
}
然後就可以暫時跳過服務器的證書無效問題。
非必要,還是不要使用啦~🤔
我要在 50+ 處修改 API 呼叫設定,真是麻煩極了~
參考:
隨意留個言吧:)~