Connecting/Subscribing to MQTT nrfCloud with .NET and MQTTnet

I am unable to connect using MQTTnet/.NET7 and wondering if I have the configuration right.  I know my certificates are correct as I can connect via OpenSSL just fine.  Hoping someone with more MQTTnet experience can lead me to a solution.

The error returned from ConnectAsync is "Authentication failed, see inner exception"

My credentials are correct as I can connect via OpenSLL.

public async Task ConnectAsync()
{

var caCertificate = new X509Certificate2("cacert.pem"); 
var cclient = X509Certificate2.CreateFromPemFile("client.pem","clientkey.pem");


string clientId = "Account-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX";
string topic = "prod/XXXXXXXXXXXXXXXXXXXXXXX/#";

X509Certificate2Collection certs = null;
certs = new X509Certificate2Collection();
certs.Add(caCertificate);
certs.Add(cclient);


var options = new MqttClientOptionsBuilder()
     .WithClientId(clientId)
     .WithTcpServer("mqtt.nrfcloud.com", 8883) // Use the appropriate port for your connection
     .WithKeepAlivePeriod( new TimeSpan(0,0,0,300))
     .WithProtocolVersion(MQTTnet.Formatter.MqttProtocolVersion.V311)
     .WithTls(new MqttClientOptionsBuilderTlsParameters
     {
          UseTls = true,
#pragma warning disable CS0618 // Type or member is obsolete
          CertificateValidationCallback = (X509Certificate x, X509Chain y, System.Net.Security.SslPolicyErrors z, IMqttClientOptions o) =>
#pragma warning restore CS0618 // Type or member is obsolete
          {
               return true;
          },
          SslProtocol = System.Security.Authentication.SslProtocols.Tls12,
          AllowUntrustedCertificates = false,
          IgnoreCertificateChainErrors = false,
          IgnoreCertificateRevocationErrors = false,

          Certificates = certs,
     })
     .Build();

_mqttClient.UseConnectedHandler(async e =>
{
     Console.WriteLine("Connected to MQTT broker");
     // Subscribe to topics or perform other actions upon successful connection
     await _mqttClient.SubscribeAsync("your_topic");
});

_mqttClient.UseDisconnectedHandler(e =>
{
     Console.WriteLine("Disconnected from MQTT broker");
});

await _mqttClient.ConnectAsync(options);
}

public void Publish(string topic, string payload)
{
     var message = new MqttApplicationMessageBuilder()
     .WithTopic(topic)
     .WithPayload(payload)
     .WithExactlyOnceQoS()
     .Build();

     _mqttClient.PublishAsync(message);
}

public void Subscribe(string topic)

     _mqttClient.UseApplicationMessageReceivedHandler(e =>
     {
          Console.WriteLine($"Received message on topic {e.ApplicationMessage.Topic}: {e.ApplicationMessage.ConvertPayloadToString()}");
     });
}


}

Parents Reply Children
  • Thanks for getting back to me, acutally as I've continued to work on this, I am now getting the following exception, " Message " Received an unexpected EOF or 0 bytes from the transport stream." .  Here is my modified code that produces this error

    public async Task<MqttClientConnectResult> ConnectAsync()
    {
         string broker = "mqtt.nrfcloud.com"; 
         int port = 8883;
         var caCertificate = new X509Certificate2("cacert.pem");


         var cclient = X509Certificate2.CreateFromPemFile(" client.pem","clientkey.pem");

         string clientId = "Account-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX";


         X509Certificate2Collection? certificates = null;
         certificates = new X509Certificate2Collection();
         certificates.Add(caCertificate);
         certificates.Add(cclient);


         List<X509Certificate2> certs = new List<X509Certificate2>
         {
              caCertificate,cclient
         };

         var tlsOptions = new MqttClientTlsOptionsBuilder()
              .WithClientCertificates(certificates)
              .WithSslProtocols(System.Security.Authentication.SslProtocols.Tls12)
              .WithCertificateValidationHandler(_ => true)
              .WithAllowUntrustedCertificates(true)
              .UseTls(true)
              .WithIgnoreCertificateChainErrors(true)
              .WithIgnoreCertificateRevocationErrors(true)
              .Build();


         var options = new MqttClientOptionsBuilder()
              .WithTcpServer(broker, port) // Use the appropriate port for your connection
              .WithClientId(clientId)
              .WithCleanSession(true)
              .WithT lsOptions( tlsOptions )
              .Build();


         MqttClientConnectResult connectResult = await _mqttClient.ConnectAsync(options,CancellationToken.None);
         // " Received an unexpected EOF or 0 bytes from the transport stream."

         return (connectResult);
    }

Related