我正在尝试使用已导入 Android 的用户可信凭据的自签名 CA 连接到端点。
不幸的是,我无法连接到这样的端点,直到我使用以下命令从 Dart 上下文加载证书:
setTrustedCertificatesBytes
。
如果我需要从 Flutter 应用程序本身管理已安装的证书,那么这是否意味着 Dart VM / Flutter 无法使用原生 Android 的用户可信凭证功能?
final rootCAString = '''-----BEGIN CERTIFICATE-----
MIIDazCCAlOgAwI...<certContentsHere>
-----END CERTIFICATE-----''';
class AcceptTrustedCertsHttpOverrides extends HttpOverrides {
@override
HttpClient createHttpClient(SecurityContext? context) {
SecurityContext trustedRootsContext = SecurityContext(withTrustedRoots: true);
// If I specifically run: `setTrustedCertificatesBytes`, any connection to HTTPS endpoint using cert signed by this rootCA will work OK.
// final certBytes = Uint8List.fromList(utf8.encode(rootCAString));
// trustedRootsContext.setTrustedCertificatesBytes(certBytes);
final client = super.createHttpClient(trustedRootsContext);
return client;
}
}
电话来自
main.dart
HttpOverrides.global = AcceptTrustedCertsHttpOverrides();
另外
network_security_config.xml
从AndroidManifest.xml
打来电话:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config xmlns:tools="http://schemas.android.com/tools">
<base-config cleartextTrafficPermitted="false">
<trust-anchors>
<certificates src="system"/>
<certificates src="user" /> <!-- ADDED THIS SPECIFICALLY -->
</trust-anchors>
</base-config>
</network-security-config>
令人惊讶的是,在 Ubuntu 上,如果我将
rootCA.crt
放在 /usr/local/share/ca-certificates
位置,那么 Flutter 应用程序会自动识别它并认为此类 CA 受信任(如预期)。
Flutter 是否可以自动加载由 Android 管理的用户可信证书或需要从应用程序管理的自签名证书?
class MyHttpOverrides extends HttpOverrides {
@覆盖 HttpClient createHttpClient(SecurityContext? context) { 返回 super.createHttpClient(context) ..badCertificateCallback = (X509Certificate cert, String 主机, int 端口) => true; } }
请将此代码放入 void main 函数中 - HttpOverrides.global = MyHttpOverrides();