behzad soltani
2 min readJul 1, 2021

--

How to use mTLS in flutter

In this article we are going to learn how to use to authenticate flutter apps when you’ve set up mTLS on your server. if you are not familiar with mTLS, in brief, it can add a layer of security to your apps so only those who have the “private key” can connect to the server .you can study more at https://developers.cloudflare.com/cloudflare-one/identity/devices/mutual-tls-authentication

(this article is hugely inspired from https://medium.com/kbtg-life/mobile-security-via-flutter-ep-1-ssl-pinning-c57f18b711f6 to provide you example for both http and Dio packages);

We are going to use both popular plugins to make network requests for flutter: http and Dio.
In flutter, it is done using SecurityContext. make sure you’ve copied the private key and the certificate in your project’s directory and you’ve added that directory to assets section of your pubspec.yaml file . In the examples ,I’ve placed them inside “assets” directory which I’ve created inside root directory of my project.

Future<SecurityContext> get globalContext async {
final List<int> keyBytes =
(await rootBundle.load(‘assets/resources/key.key’))
.buffer
.asInt8List();
final List<int> certificateChainBytes =
(await rootBundle.load(‘assets/resources/key_crt.crt’))
.buffer
.asInt8List();
SecurityContext sc = SecurityContext(withTrustedRoots: false);
sc.usePrivateKeyBytes(keyBytes);
sc.useCertificateChainBytes(certificateChainBytes);
return sc;
}

first we are going to write a getter which returns a Future<SecurityContext>. load both key and certificate files, initialize the SecurityContext object and then by calling “usePrivateKeyBytes()” and “keyBytes” variable as its argument, we specify our private key,
After that , call “useCertificateChainBytes()” and “certificateChainBytes” as its argument, we specify the certificate.

In this step, initialize your HttpClient and pass globalContext getter which we built earlier. and pass that object to IoClient and we’re done; you can connect to your server using your keys.

In the provided example, I’ve implemented both for both packages. you can check out the example on github:

https://github.com/xoltawn/mtls_example_flutter

--

--