Secure the MQTT broker

In our first episode of the Home Automation series we installed the Mosquitto MQTT broker in Ubintu Server. In this Episode we will look at securing the broker better and installing Node-Red to help monitor and administrate the MQTT broker.


Now we have Ubuntu server installed and the Mosquitto MQTT broker installed it is now time to look at the security of the broker. To make it more secure so that people outside can not contril your devices we will add a username and password to the MQTT broker.

We use the password file generating utility that comes with Mosquitto, to create the user “steve” with password “password”. by entering the following command:

#sudo mosquitto_passwd -c /etc/mosquitto/passwd steve
Password: password

Next we create a configuration file for Mosquitto that will point to the password file we just created with the above command. The nano editor will open an empty file when running this command:

sudo nano /etc/mosquitto/conf.d/default.conf

Add these lines to the new empty file:

allow_anonymous false
password_file /etc/mosquitto/passwd

Press “Ctrl+O” then “Enter” then “Ctrl-X” to save and exit this file

Restart Mosquitto:

sudo systemctl restart mosquitto

If you try to run the command #mosquitto_sub -t “test” it will now fail to let you subscribe to the “test” topic because it will be requiring our username and password. So to test the username and password works enter:

mosquitto_sub -t "test" -u "steve" -P "password" &

Don’t forget the “&” which will force this command to run in the background. The reason we are going to do it this way is that we are going to publish a message to the test topic and see it received and displayed on the screen by the mosquitto_sub subscription, hence testing both publish and subscription of the message sent to/from the “test” topic.

Now we have the mosquitto_sub running in the background lets publish our first message.

 mosquitto_pub -t "test" -m "message published - Hello World" -u "steve" =P "password"

Once you press enter you should see “message published – Hello World” appear on the next line straight away if all is working OK.

In the next tutorial I will be looking at how to install the Node-Red onto our Ubuntu server we setup.

Leave a Reply

Your email address will not be published. Required fields are marked *