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.

    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

a Flutter and Laravel Developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

I, OS: debug your mind’s code — and hack yourself happy

HK LandsD Map Sheet Index Query

You won’t want to leave your home office ever again

Monitoring Mysql-server

Store revisions of content in PostgreSQL

Terraform patterns and tricks I use every day

Design Patterns: Prototype

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
behzad soltani

behzad soltani

a Flutter and Laravel Developer

More from Medium

The Form Widget — Flutter

How To Upgrade Your Old Flutter Projects (include migration to null safety)

Flutter Measure Formatter Plugin

Recipe for a Private Flutter Package