1

我是一个新的 .NET 核心用户,试图学习如何使用MQTTnet在 MacOS Catalina 上将托管客户端与 TLS 连接起来。

我正在尝试从 ASP.NET Core 3 后台服务连接到 Mosquitto 代理。使用MqttExplorer,我可以使用用户名、密码和服务器证书 (CA) 文件通过 TLS 成功连接到服务器。所以,我知道 Mosquitto Broker 配置正确。

但是,我无法通过 MQTTnet 实现这一点。

using (var fileStream = new FileStream(_Config.Tls.CACerts, FileMode.Open))
                using (var memoryStream = new MemoryStream((int)fileStream.Length))
                {
                    fileStream.CopyTo(memoryStream);

                    _Logger.LogInformation($"Read file stream with length {memoryStream.Length} bytes, trying to connect with options:");
                    _Logger.LogInformation($"mqtt://{_Config.UserName}:{_Config.Password}/{_Config.Host}:{_Config.Port}");

                    _MqttOptions = new ManagedMqttClientOptionsBuilder()
                        .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                        .WithClientOptions(new MqttClientOptionsBuilder()
                            .WithClientId(Guid.NewGuid().ToString())
                            .WithCredentials(_Config.UserName, _Config.Password)
                            .WithTcpServer(_Config.Host, _Config.Port)
                            .WithTls(
                                o =>
                                {
                                    o.UseTls = true;
                                    o.AllowUntrustedCertificates = true;
                                    o.SslProtocol = SslProtocols.Tls12;
#if WINDOWS_UWP
                                    o.Certificates = new List<byte[]>
                                    {
                                        new X509Certificate(memoryStream.ToArray()).Export(X509ContentType.Cert)
                                    };
#else
                                    o.Certificates = new List<X509Certificate>
                                    {
                                        new X509Certificate(memoryStream.ToArray())
                                    };
#endif

                                    o.CertificateValidationHandler = (context) =>
                                    {
                                        _Logger.LogInformation($"SSL POLICY ERRORS {context.SslPolicyErrors.ToString()}");
                                        return true;
                                    };
                                }
                            )
                            .Build())
                        .Build();
                }

我收到以下异常:

MQTTnet.Exceptions.MqttCommunicationException: Authentication failed, see inner exception.
 ---> System.Security.Authentication.AuthenticationException: Authentication failed, see inner exception.
 ---> Interop+AppleCrypto+SslException: bad protocol version
   --- End of inner exception stack trace ---
   at System.Net.Security.SslStream.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, ExceptionDispatchInfo exception)
   at System.Net.Security.SslStream.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslStream.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslStream.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslStream.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslStream.PartialFrameCallback(AsyncProtocolRequest asyncRequest)
--- End of stack trace from previous location where exception was thrown ---
   at System.Net.Security.SslStream.ThrowIfExceptional()
   at System.Net.Security.SslStream.InternalEndProcessAuthentication(LazyAsyncResult lazyResult)
   at System.Net.Security.SslStream.EndProcessAuthentication(IAsyncResult result)
   at System.Net.Security.SslStream.EndAuthenticateAsClient(IAsyncResult asyncResult)
   at System.Net.Security.SslStream.<>c.<AuthenticateAsClientAsync>b__64_2(IAsyncResult iar)
   at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
--- End of stack trace from previous location where exception was thrown ---
   at MQTTnet.Implementations.MqttTcpChannel.ConnectAsync(CancellationToken cancellationToken)
   at MQTTnet.Implementations.MqttTcpChannel.ConnectAsync(CancellationToken cancellationToken)
   at MQTTnet.Internal.MqttTaskTimeout.WaitAsync(Func`2 action, TimeSpan timeout, CancellationToken cancellationToken)
   at MQTTnet.Adapter.MqttChannelAdapter.ConnectAsync(TimeSpan timeout, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at MQTTnet.Adapter.MqttChannelAdapter.WrapException(Exception exception)
   at MQTTnet.Adapter.MqttChannelAdapter.ConnectAsync(TimeSpan timeout, CancellationToken cancellationToken)
   at MQTTnet.Client.MqttClient.ConnectAsync(IMqttClientOptions options, CancellationToken cancellationToken)
>> [2020-10-02T16:07:03.9254330Z] [4] [MqttClient] [Verbose]: Disconnecting [Timeout=00:00:10]
>> [2020-10-02T16:07:03.9255750Z] [4] [MqttClient] [Verbose]: Disconnected from adapter.
>> [2020-10-02T16:07:03.9256240Z] [4] [MqttClient] [Info]: Disconnected.

此外,明确尝试添加WithProtocolVersion(MQTTnet.Formatter.MqttProtocolVersion.V311)到客户端选项生成器。

有人能帮忙吗?

4

2 回答 2

1

设法让它工作!

问题是 mosquitto 代理配置为仅使用 Tls v1.3。但是,macOS 环境似乎不支持 dotnet core 3.1 tls1.3?如果 openssl 1.1.1 可用,它在 Linux 环境中可用。

我已将 mosquitto 代理配置降级为使用 tls 1.2 版,上面的代码现在可以连接。

如果有人设法让 dotnet core 3.1 客户端使用 tlsv1.3 连接到 mosquitto 代理,那么任何细节都将不胜感激。

于 2020-10-05T15:06:13.817 回答
0

github上有类似的问题

作为一种解决方法,一位用户提出了以下 cli 命令:

dotnet dev-certs https
dotnet dev-certs https --trust

一些关于它们的文档。

信任 Windows 和 macOS 上的 ASP.NET Core HTTPS 开发证书

安装 .NET Core SDK 会将 ASP.NET Core HTTPS 开发证书安装到本地用户证书存储。证书已安装,但不受信任。要信任证书,请执行一次性步骤以运行 dotnet dev-certs 工具:

于 2020-10-03T22:13:02.940 回答