I am new with MQTT protocol. When I searched for an MQTT server I found that Mosquitto broker is one of the most used one and therefore I have started using it. I have to develop an MQTT client on C#/.NET and I found only the M2Mqtt project and this C# MQTT client example.
I managed to install Mosquitto broker on Windows 10 and change the access control list using topics. Using MqttClient
I am able to connect to the broker with an username, subscribe to topics and publish them with the following code.
Connect:
byte result = this.mqttClient.Connect(Guid.NewGuid().ToString(), username, string.Empty);
Subscribe:
this.mqttClient.Subscribe(new string[] { topic }, new byte[] { 2 });
Publish:
ushort result = this.mqttClient.Publish(topic, message, MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, true);
Now I want to add security in communications. I followed these steps to create the CA certificate, the server key and server certificate (I created the certificates twice). I changed the mosquito.conf
file as explained in the link:
port 8883
cafile C:\mosquitto\certs\ca.crt
certfile C:\mosquitto\certs\server.crt
keyfile C:\mosquitto\certs\server.key
I don't know if it is necessary, but I added the ca.crt
to the Trusted Root Certificates following these steps.
I changed the client to use the CA certificate in the connection:
//this.mqttClient = new MqttClient(brokerAddress);
X509Certificate caCertificate = new X509Certificate("ca.crt");
this.mqttClient = new MqttClient(brokerAddress, 8883, true, caCertificate, null, MqttSslProtocols.TLSv1_0);
A copy of the ca.crt
file is in the same folder of the .exe
file. When I run the application I always get the same exception:
uPLibrary.Networking.M2Mqtt.Exceptions.MqttConnectionException
: Exception connecting to the broker- [Inner exception]
System.Security.Authentication.AuthenticationException
: The remote certificate is invalid according to the validation procedure.
Do you know if I am missing something?