Flutter Native Certs

Pub License: MIT

A Flutter plugin to use the certificates from the native certificate store on every platform.

Background

Flutter does not use the native certificate store on every platform.

Android

Flutter uses a custom certificate bundle of trusted root certificates. There are several issues related to this topic:

This issue is especially important if the dart:io:HttpClient or the IOClient must be used, because it does rely on SecurityContext.defaultContext by default.

Side Note: network_security_config.xml

Normally for trusting user certificates on Android a network_security_config.xml similar to the sample below would need to be placed inside android/app/src/main/res/xml:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
  <base-config>
    <trust-anchors>
      <certificates src="system"/>
      <certificates src="user"/>
    </trust-anchors>
  </base-config>
</network-security-config>

This is not necessary for flutter_native_certs, but is still recommended if a package like cronet_http is used which does consider user certificates even on Android.

Getting Started

This plugin provides a custom SecurityContext which includes certificates loaded from the native certificate store at startup.

Please note that due to the architecture of this plugin user installed certificates are not trusted until the app is fully restarted.

Installation

Run

flutter pub add flutter_native_certs

in order to install the plugin.

Initialization

The plugin must be initialized at application startup.

It is recommended to make the main function async and initialize the plugin there, before calling runApp:

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  try {
    await FlutterNativeCerts.instance.initialize();
  } on PlatformException catch (e) {
    debugPrint(
      'Failed to initialize FlutterNativeCerts plugin: ${e.toString()}',
    );
  }

  runApp(const MyApp());
}

Usage

The plugin provides a custom SecurityContext that must be used everywhere, where the native certificates should be used.

HttpClient

In order to use the plugin with the HttpClient from dart:io, supply its SecurityContext to the constructor of the client:

HttpClient(
    context: FlutterNativeCerts.instance.securityContext
)

IOClient

If the plugin should be used with the IOClient from the http package, a custom HttpClient must be created as demonstrated above and then this client must be supplied to the constructor of the IOClient:

IOClient(
    HttpClient(
        context: FlutterNativeCerts.instance.securityContext
    )
)

Platform Support

While the plugin supports all platforms, it is currently only useful on Android.

On all platforms except Android FlutterNativeCerts.instance.securityContext will be the same as SecurityContext.defaultContext regardless of the parameters specified when calling FlutterNativeCerts.instance.initialize().

License

Released under the terms of the MIT License.