How to do SSL pinning via self generated signed certificates in flutter?

There isn’t enough detail in the question, so this answer is based on some assumptions:

  1. Your APIs are HTTPS
  2. You are talking about validating a server-side self-signed HTTPS certificate
  3. You are using package:http as the http client
  4. No client-side certificates

package:http uses dart:io HttpClient under the hood, and HttpClient has a several features to allow for certificate validation. Since a self-signed server certificate will be untrusted by the client, the client will call the badCertificateCallback allowing you to validate the server certificate yourself, for example:

HttpClient httpClient = new HttpClient()
  ..badCertificateCallback =
  ((X509Certificate cert, String host, int port) {
    // tests that cert is self signed, correct subject and correct date(s) 
    return (cert.issuer == cert.subject &&
        cert.subject == 'MySelfSignedCertCN' &&
        cert.endValidity.millisecondsSinceEpoch == 1234567890);
  });

IOClient ioClient = new IOClient(httpClient);
// use ioClient to perform get/post operations from package:http

// don't forget to call ioClient.close() when done
// note, this also closes the underlying HttpClient

Leave a Comment