公司服务端更新了https,而使用的是自签名的证书,导致iOS开发过程中调用HTTPS接口时,证书不被信任,出现了Default TLS Trust evaluation failed。
解决办法如下:
NSURLSession初始化时添加代理,然后在代理方法中做证书相关处理
NSURL *url = [NSURL URLWithString:[mutableStringUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];
NSURLSessionDataTask * dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
failureBlock(error);
} else {
NSString * result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
successBlock(result);
}
}];
[dataTask resume];
解决方式有两种:
1.跳过TLS认证,信任所有证书
2.设置白名单,把签名证书加到工程中,做校验
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler {
1.方法一
if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]){
NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
if(completionHandler)
completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
}
2.方法二
// SecTrustRef servertrust = challenge.protectionSpace.serverTrust;
// SecCertificateRef certi= SecTrustGetCertificateAtIndex(servertrust, 0);
// NSData *certidata = CFBridgingRelease(CFBridgingRetain(CFBridgingRelease(SecCertificateCopyData(certi))));
// NSString *path = [[NSBundle mainBundle] pathForResource:@"zwp" ofType:@"cer"];
// NSLog(@"证书 : %@",path);
// NSData *localCertiData = [NSData dataWithContentsOfFile:path];
// if ([certidata isEqualToData:localCertiData]) {
// NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:servertrust];
// [challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
// completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
// NSLog(@"服务端证书认证通过");
// }else {
// completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
// NSLog(@"服务端认证失败");
// }
}
网友评论