Client Certificate Authentication (mTLS) with Flutter

flutter Mar 20, 2020

Client Certificate Authentication has become popular in new generation Open Banking Services so in this article we will examine how to make mTLS Auth with Flutter.

We will use Dio package

Add dependency

dependencies:
  dio: ^3.0.9

Add Assets

flutter:
  assets:
  - res/certs/

Load Certificates

 final List<int> certificateChainBytes =
    (await rootBundle.load('res/certs/domain.crt')).buffer.asInt8List();
 final List<int> keyBytes =
    (await rootBundle.load('res/certs/domain.rsa')).buffer.asInt8List();

Add SecurityContext to HttpClient

(dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate  = (client) {
      SecurityContext sc = new SecurityContext(withTrustedRoots: true);
      sc.useCertificateChainBytes(certificateChainBytes);
      sc.usePrivateKeyBytes(keyBytes);
      HttpClient httpClient = new HttpClient(context: sc);
      return httpClient;
    };

if you are using self signed certificate skip certificate validation like this

httpClient.badCertificateCallback=(X509Certificate cert, String host, int port){return true;};

Full Code Request with mTLS

  void getHttp() async {
    dio = new Dio();
    final List<int> certificateChainBytes =
    (await rootBundle.load('res/certs/domain.crt')).buffer.asInt8List();
    final List<int> keyBytes =
    (await rootBundle.load('res/certs/domain.rsa')).buffer.asInt8List();


    (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate  = (client) {
      SecurityContext sc = new SecurityContext(withTrustedRoots: true);
      sc.useCertificateChainBytes(certificateChainBytes);
      sc.usePrivateKeyBytes(keyBytes);
      HttpClient httpClient = new HttpClient(context: sc);
      httpClient.badCertificateCallback=(X509Certificate cert, String host, int port){
        return true;
      };
      return httpClient;
    };

    try {
      Response response = await dio.get("https://yourmtlsauthservice.com");
      print(response);
    } catch (e) {
      print(e);
    }
  }

Tags

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.