Ensuring secure communication between devices is crucial when working with MQTT. In the previous parts of this MQTT series, you set up communication between two ESP8266 devices and exchanged sensor data. However, security measures were not yet implemented. Without proper security, an unauthorized user could intercept your data or disrupt your system.
This tutorial will guide you through integrating authentication so that your ESP8266 devices require a username and password to connect to the MQTT broker. While this does not guarantee complete security, it is a significant step toward protecting your data and devices.
Configuring the MQTT Broker
To secure your MQTT broker, you need to enable authentication on the Mosquitto broker running on your Raspberry Pi.
Step 1: Creating the Password File
Use the mosquitto_passwd
command to create a password file and add users. Enter the following command in the terminal, replacing <username>
with a username of your choice:
You will then be prompted to enter a password. Choose a strong password—resources such as the Boston University provide guidelines for secure passwords. You will later use this password in your ESP8266 sketches.
To add another user without overwriting the existing password file, use this command, replacing <username>
and <password>
accordingly:
Step 2: Configuring Mosquitto
Next, edit the Mosquitto configuration file by running:
Append the following lines at the end of the file:
These settings disable anonymous access and specify the path to the password file.
Step 3: Restarting the Mosquitto Service
To apply the changes, restart the Mosquitto broker using:
Configuring the ESP8266 Clients
Now, update your ESP8266 sketches so that they authenticate with a username and password when connecting to the broker.
Step 1: Adding Authentication Details
At the beginning of your sketch, define the username and password:
Step 2: Modifying the Reconnection Function
Use these credentials in the reconnect()
function. The updated function should look like this:
Step 3: Testing the Connection
Update your ESP8266 sketches with these changes and test the connection. If everything works as expected, you have successfully secured your MQTT system!