Configuring Mosquitto client with Authentication

Prerequisites:
1. Docker
2. Require an existing mosquitto client running on Local or on Virtual Machine or in docker to generate secret key using mosquitto_passwd from command-line

If you dont have client running on your machine, follow this article https://azuregravy.com/deploying-mosquitto-message-broker-with-docker/ to run mosquitto client on machine using docker

As I am already running my mosquitto client using docker, I will run the following docker exec command to generate passwd hash by running following command:

docker exec -it mosquitto-server mosquitto_passwd -b -c passwd parulbedi mosquitto@1234

Print the value of secret on terminal using cat command (for temporary purpose store this key locally on notepad)

docker exec -it mosquitto-server cat passwd
You will get a similar output as follows:
parulbedi:$7$101$sSJ7yv075mkm8E2S$DpESCEinRzLnuHLTKm4ynGMJOXDo9Kznc9/8cUTGrFQSQxJmGwmpDJc0DFA150eMGTVnC5oUPuP8LTOMbjfd/w==

Exit from container, goto mosquitto directory & create a new directory with name mq_passwd

Store the secret key in mq_passwd directory with filename mosquitto.passwd

Stop & remove currently running mosquitto client docker container

goto mosquitto/mq_config directory & update allow_anonymous to false & add password_file parameter in the mosquitto.conf file

allow_anonymous false
password_file /mosquitto/config/mosquitto.passwd

Update docker run command to add password configuration in mosquitto client,

docker run -d --name mosquitto-server -p 1883:1883 -v "$HOME/mosquitto/mq_config:/mosquitto/config" -v "$HOME/mosquitto/mq_data:/mosquitto/data" -v "$HOME/mosquitto/mq_log:/mosquitto/log" -v "$HOME/mosquitto/mq_passwd/mosquitto.passwd:/mosquitto/config/mosquitto.passwd" eclipse-mosquitto

Verify both the updated configurations are mounted inside the container


1

2

Lets try to send a MQTT message directly from command line by running the following command

mosquitto_pub -h localhost -t test -m "test"

Note: I got an error connection because now I need to provide username & password in order to run my test command

mosquitto_pub -h localhost -t test -m "test" -u "parulbedi" -P "mosquitto@1234"

Here,
-u parameter requires username
-P parameter requires password

This time terminal move to next-line without any error, this means that command executes successfully