HarmonyOS 鸿蒙Next中如何跳过证书检查
HarmonyOS 鸿蒙Next中如何跳过证书检查 如题,如何跳过证书检查?
【背景知识】
Remote Communication Kit提供了网络数据请求功能,相较于Network Kit中HTTP请求能力,更具易用性,且拥有更多的功能。Remote Communication Kit支持忽略证书校验。参考文档:自定义证书校验。
【解决方案】
方案一:
自定义requestConfig对象,重写ValidationCallback。remoteValidation在实际的证书验证中,这个函数会检查证书的有效性等信息,这里返回true来忽略证书校验,样例代码如下:
import { BusinessError } from '@ohos.base';
import promptAction from '@ohos.promptAction';
import { rcp } from '@kit.RemoteCommunicationKit';
import { util } from '@kit.ArkTS';
async testRcpConnection() {
this.message = '正在建立连接...';
try {
const requestConfig: rcp.Configuration = {
security: {
remoteValidation: (context: rcp.ValidationContext) => {
// 重写ValidationCallback,直接返回true表示验证通过
console.info("[index]证书验证");
return true;
}
}
};
// 服务器地址
const kHttpServerAddress = "https://xxx.xx.xx.x:xxxx";
// 创建一个get请求对象
const request = new rcp.Request(kHttpServerAddress, 'GET');
// 传入自定义的配置项,处理请求
const session = rcp.createSession({ requestConfiguration: requestConfig });
const resp = await session.fetch(request);
let decoder: util.TextDecoder = util.TextDecoder.create('utf-8');
let body: string = decoder.decodeWithStream(new Uint8Array(resp.body));
// 显示提示信息,包含响应成功的消息和响应体内容
promptAction.showToast({ message: `[index]Response succeeded: ${body}` });
} catch (error) {
let err = error as BusinessError;
this.message = `[index]连接失败: ${err.code}`;
promptAction.showToast({ message: `错误: ${err.message}` });
console.error("[index]连接错误:", err);
}
}
方案二:
设置remoteValidation参数为skip,用于跳过证书验证,样例代码如下:
// Configure security settings
const securityConfig: rcp.SecurityConfiguration = {
remoteValidation: "skip"
};
// Use the security configuration in the session creation
const sessionWithSecurityConfig = rcp.createSession({ requestConfiguration: { security: securityConfig } });
更多关于HarmonyOS 鸿蒙Next中如何跳过证书检查的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中,可通过配置网络安全策略跳过证书检查。在应用的config.json
文件中,添加<cleartextTrafficPermitted>
标签并设置为true
,允许明文传输。同时,在代码中使用http
协议替代https
进行网络请求,以避免证书验证。注意,此操作会降低通信安全性,仅建议在开发或测试环境中使用。
在HarmonyOS Next中,出于安全考虑,不建议跳过证书检查。系统强制要求使用有效的SSL/TLS证书来确保网络通信的安全性。若在开发或测试环境中遇到证书问题,应通过以下方式解决:
- 使用官方CA签发的有效证书:部署由可信CA(如Let’s Encrypt、DigiCert)签发的证书,避免自签名证书。
- 配置正确的证书链:确保服务器返回完整的证书链,避免中间证书缺失。
- 更新系统根证书:检查设备是否包含最新根证书,可通过系统更新或手动导入缺失的根证书。
- 开发调试模式:在开发阶段,使用
HttpClient
的setSslSocketFactory
方法配置自定义SSLSocketFactory
,但仅限于非生产环境。
示例代码(仅限开发测试):
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{new X509TrustManager() {
@Override public void checkClientTrusted(X509Certificate[] chain, String authType) {}
@Override public void checkServerTrusted(X509Certificate[] chain, String authType) {}
@Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
}}, new SecureRandom());
HttpClient.create().setSslSocketFactory(sslContext.getSocketFactory());
注意:生产环境必须使用有效证书,跳过检查会导致严重安全风险,且违反应用上架规范。