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()}");
});
}
}