getWebSocketTLSContext function

SecurityContext? getWebSocketTLSContext()

Get TLS options for WebSocket connections.

Implementation

SecurityContext? getWebSocketTLSContext() {
  final mtlsConfig = getMTLSConfig();
  final caCerts = getCACertificates();

  if (mtlsConfig == null && caCerts == null) return null;

  final context = SecurityContext(withTrustedRoots: true);

  if (mtlsConfig?.cert != null) {
    try {
      context.useCertificateChainBytes(utf8.encode(mtlsConfig!.cert!));
    } catch (_) {}
  }

  if (mtlsConfig?.key != null) {
    try {
      context.usePrivateKeyBytes(
        utf8.encode(mtlsConfig!.key!),
        password: mtlsConfig.passphrase,
      );
    } catch (_) {}
  }

  if (caCerts != null) {
    for (final cert in caCerts) {
      try {
        context.setTrustedCertificatesBytes(utf8.encode(cert));
      } catch (_) {}
    }
  }

  return context;
}