I'm having issues with certificate verification in a WebSocket connection in Flutter

93 Views Asked by At

various forums, but I haven't managed to disable the badCertificateCallback or make Flutter trust specific certificates. What recommendations or approaches would you suggest to address this problem?


  Future<List<Acumulado>?> _connectToWebSocket(String id) async {
    Completer<List<Acumulado>> completer = Completer();
    List<Acumulado> maquinas = [];

    try {
      final String webSocketUrl =
          '${widget.constantes.appSettings!.address.replaceFirst("http", "ws")}:8887/${widget.nombrebd}';

      // Crear un cliente HTTP personalizado para aceptar certificados autofirmados
      final httpClient = new HttpClient()
        ..badCertificateCallback =
            (X509Certificate cert, String host, int port) => true;

      // Utilizar el cliente personalizado para el WebSocket
      final ioClient = new IOClient(httpClient);

      _channel = IOWebSocketChannel.connect(
        Uri.parse(webSocketUrl),
        headers: {'session': widget.constantes.session, 'authenticate': 'true'},
      );

      _channel.sink.add('{"clase":"request","datos":[{}]}');
      _channel.stream.listen((message) {
        var data = json.decode(message);
        print("data: $data $message");
        if (data['clase'] == 'estado') {
          var message = data['datos'][0]['mensaje'];
          print(message);
          maquinas = (data['datos']
              .map<Acumulado>((item) => Acumulado.fromJson(item))
              .toList());
          _channel.sink.add('{"clase":"request","datos":[{}]}');
          completer.complete(maquinas);
        }
      });
    } catch (e) {
      // Manejar otras excepciones
      print('Error connecting to WebSocket: $e');
      completer.completeError(e);
    } finally {
      HttpOverrides.global = null; // Restablecer la anulación global de HTTP
    }

    return completer.future;
  }

When I get to this part in my view I get the following exception:

[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: WebSocketChannelException: WebSocketChannelException: HandshakeException: Handshake error in client (OS Error: 
    CERTIFICATE_VERIFY_FAILED: self signed certificate(../../third_party/boringssl/src/ssl/handshake.cc:393))

I waited for the object to return and tried to rebuild the class by adding the next class:

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

There are 0 best solutions below