【问题标题】:ClientWebsocket SSL Certificate Verification FailedClientWebsocket SSL 证书验证失败
【发布时间】:2020-11-08 17:54:20
【问题描述】:

我正在用 Xamarin.Forms 编写一个面向 .Net Standard 2.1 的应用程序,主要专注于 Android 构建。

我有一些 websocket 客户端代码可以连接到我的安全自签名服务器;但是,它不会验证证书。我发现了一些使用 ServicePointManager 进行验证回调或 ClientWebSocketOptions.RemoteCertificateValidationCallback 的参考,但在连接时都没有调用回调。 这是连接代码:

public async Task Connect(string url) {
            if (client != null) {
                if (client.State == WebSocketState.Open) return;
                else client.Dispose();
            }
            ServicePointManager.ServerCertificateValidationCallback = ValidateServerCert;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
            client = new ClientWebSocket();
            client.Options.AddSubProtocol("json");
            client.Options.UseDefaultCredentials = false;
            client.Options.RemoteCertificateValidationCallback = ValidateServerCert;
            if (CTS != null) CTS.Dispose();
            CTS = new CancellationTokenSource();
            Console.WriteLine("TBL: Connecting to " + url + "...");
            try {
                await client.ConnectAsync(new Uri(url), CTS.Token);
            } catch (Exception e) {
                Console.WriteLine("TBL: Ex: " + e);
            }
            Console.WriteLine("TBL: Client state: " + client.State);
            if (client.State == WebSocketState.Open) {
                OnConnect?.Invoke(); // if no callbacks registered, it's null
                Console.WriteLine("TBL: Websocket connected");
                await Task.Factory.StartNew(ReceiveLoop, CTS.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
            }
        }

将此打印在设备日志中(我还不能嵌入图片):

Device Log Output

我已经在互联网上搜索了答案/提示,大多数似乎都适用于 HTTPS 而不是 Websockets(或者至少他们的解决方案似乎不起作用)。无论我如何安排,我都无法调用验证回调。非常感谢任何帮助。

【问题讨论】:

    标签: c# ssl websocket xamarin.android .net-standard-2.1


    【解决方案1】:

    https://stackoverflow.com/a/26336847/9516

    这接受所有证书,甚至是自签名证书: ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-23
      • 1970-01-01
      • 1970-01-01
      • 2021-09-28
      • 2021-10-08
      • 2016-11-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多