Flutter https with self signed certificate
While Pascal's answer works, it only applies to the dart:io HttpClient
.To apply the badCertificateCallback
to the http
package's Client
instances, do the following:
Create a class that overrides HttpOverrides
in the following way:
class DevHttpOverrides extends HttpOverrides { @override HttpClient createHttpClient(SecurityContext context) { return super.createHttpClient(context) ..badCertificateCallback = (X509Certificate cert, String host, int port) => true; }}
Then in your main, instantiate your class as the global HttpOverride:
HttpOverrides.global = new DevHttpOverrides();
This should make all Client ignore bad certificates and is therefore onl;y recommended in development.Credit goes to this issue: https://github.com/dart-lang/http/issues/458
While developing you can use the badCertificateCallback
callback of HttpClient and just return true
. This will accept all bad certificates.
HttpClient client = HttpClient() ..badCertificateCallback = ((X509Certificate cert, String host, int port) => true);
To accept a specific bad certificate you may experiment with this code from here: https://github.com/dart-lang/http/issues/14#issuecomment-311184690
import 'dart:io';import 'package:http/http.dart' as http;bool _certificateCheck(X509Certificate cert, String host, int port) => host == 'local.domain.ext'; // <- changeHttpClient client = new HttpClient() ..badCertificateCallback = (_certificateCheck);
Amazing @Wecherowski, I think more safe way to do this is to check the other details and return true.
Something like:
HttpClient createHttpClient(SecurityContext? context) { return super.createHttpClient(context) ..badCertificateCallback = (X509Certificate cert, String host, int port) { if (host.isNotEmpty && host == 'xyz.example.com') { return true; } else { return false; } };