Closed NguyenTam closed 2 months ago
Hi @NguyenTam
Seems to me you are not targeting the TLS port, it should be 8883, the code below works for me running in net472
IMqttClient mqttClient = new MqttFactory().CreateMqttClient();
MqttClientConnectResult connAck = await mqttClient.ConnectAsync(new MqttClientOptionsBuilder()
.WithTcpServer("<yourbroker>.eventgrid.azure.net", 8883)
.WithCredentials("client1")
.WithProtocolVersion(MQTTnet.Formatter.MqttProtocolVersion.V500)
.WithTlsOptions(new MqttClientTlsOptionsBuilder()
.WithClientCertificates(new X509Certificate2Collection(new X509Certificate2("client1.pfx", "<yourpassword>")))
.Build())
.Build());
Console.WriteLine($"Client Connected: {mqttClient.IsConnected} with CONNACK: {connAck.ResultCode}");
mqttClient.ApplicationMessageReceivedAsync += async m => await Console.Out.WriteAsync(
$"Received message on topic: '{m.ApplicationMessage.Topic}' with content: '{m.ApplicationMessage.ConvertPayloadToString()}'\n\n");
MqttClientSubscribeResult suback = await mqttClient.SubscribeAsync("sample/+", MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce);
suback.Items.ToList().ForEach(s => Console.WriteLine($"subscribed to '{s.TopicFilter.Topic}' with '{s.ResultCode}'"));
MqttClientPublishResult puback = await mqttClient.PublishStringAsync("sample/topic1", "hello world!", MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce);
Console.WriteLine(puback.ReasonString);
Console.ReadLine();
Thank you @rido-min for helping,
When I simplified to your way, then certificate authentication work ✅. Thanks for your help.
Hello, I would like to ask question relating certificate authentication to Azure.
I tried to login to Azure using pfx-file, which I created from openssl-command:
openssl.exe pkcs12 -export -in <client pem file> -inkey <client key file> -out <client pfx file>
Then I tried to connect to Azure cloud roughly this way:
but I got Exception:
Someone know where is the problem? I am still stuck at .NET 472 framework, so I can't use CreateFrom*PEM*-methods yet. The client's pem-file and key-file work on MQTT Explorer, I used them to publish messages, no CA-file is needed.
I have read quite a lot sites, mostly written by @rido-min ,but seems for .NET Core. I have asked AI for help which asked me to install BouncyCastle.Crypto.dll to create own ImportFromPem-method, but the implementation involve calling PemReader-method which is not available in .net framework.
Could someone direct me a bit, so I can publish messages to Azure's broker?