Massoud the Great
Massoud the Great

Reputation: 63

Flutter app cannot make socket connection with certificate handshake error CERTIFICATE_VERIFY_FAILED

One might say this question is a duplicate, but it is not, as other questions this type are about self-signed certificate, and about development environment.

I have a valid certificate from letsencrypt.org, but I cannot manage to establish socket connection. I have a nodejs server where I use the module "ws", and use the package "web_socket_channel" in flutter.

I had the same handshake problem for all my http requests (using requests package) but I could bypass it adding option verify to false:

 final r = await Requests.get(app_url, verify: false);

I don't like this solution as it is not secure for production environment. I would like a solution that would suit production environment.

Thanks to you all

Upvotes: 2

Views: 801

Answers (2)

Walulya francis
Walulya francis

Reputation: 573

you can extend HttpOverides class and override createHttpClient method to change the securityContext. it happens to mostly users with android 7 and below.

  class MyHttpOverrides extends HttpOverrides {
  @override
  HttpClient createHttpClient(SecurityContext? context) {
    return super.createHttpClient(context)
      ..badCertificateCallback =
          (X509Certificate cert, String host, int port) => true;
   }
  }

and declare it in your main

Future<void> main() async {
  HttpOverrides.global = MyHttpOverrides();
 runApp(const MyApp());
}

if your running WebSocket channel in background service where you need to reconnect to the server regularly when the WebSocket is disconnected, make sure you add HttpOverrides.global = MyHttpOverrides(); in your start method if your using flutter_background_service package like this

@pragma('vm:entry-point')
Future<void> onStart(ServiceInstance service) async {
  HttpOverrides.global = MyHttpOverrides();
// Your Websocket connection code goes here
}

Upvotes: 1

Massoud the Great
Massoud the Great

Reputation: 63

For every one reading this, the problem was not from my flutter code, it was from my nginx configuration, I had to add the following lines to /etc/nginx/conf.d/sysmon.conf file:

location / {
        proxy_set_header   X-Forwarded-For $remote_addr;
        proxy_http_version  1.1;
        proxy_set_header    Upgrade $http_upgrade;
        proxy_set_header    Connection "upgrade";
        proxy_set_header    Host $http_host;
        proxy_set_header    X-Real-IP $remote_addr;
        proxy_set_header   Host $http_host;
        proxy_pass         http://<SERVER_IP>:<PORT>;
    }

Upvotes: 2

Related Questions