Setting up Authentication in Mosquitto MQTT Broker

Mosquitto is one of the most famous MQTT broker. Its very easy to install and easy to use. But when I wanted to set up the username/password authentication I found it but difficult to setup in my Ubuntu 14.04 machine.

After reading many articles and answers, following are the steps I found to make it work.

  1. Install the latest Mosquitto distribution.

If you have installed Mosquitto simply using apt-get install in Ubuntu you might be having a old version of it. Therefor we have to point to to a new repository and install the latest. Simplest way to check whether your Mosquitto version supports this tutorial by going directly into step (3) and try it out. If you get a command not found response, you have to install the new Mosquitto version. And you don’t even have to remove the old version in order to do this.

Run following commands,

wget http://repo.mosquitto.org/debian/mosquitto-repo.gpg.key
sudo apt-key add mosquitto-repo.gpg.key
cd /etc/apt/sources.list.d/
sudo wget http://repo.mosquitto.org/debian/mosquitto-wheezy.list
sudo apt-get update
sudo apt-get install mosquitto

2. If you have just installed the Mosquitto broker, make sure its stopped (to be in the safe side)

sudo stop mosquitto

3. Creating the new password file

Password file will contain your username and the encrypted password. Run the following command to create and add a user to this file.

sudo mosquitto_passwd -c /etc/mosquitto/passwd <user_name>

Then, you will be asked for your password twice, enter that too.

4. Now we have to give the location of the password file to the Mosquitto broker config file. To do that open the mosquitto.conf file using the following command,

sudo gedit /etc/mosquitto/mosquitto.conf

And add following two entries to the mosquitto.conf file,

password_file /etc/mosquitto/passwd
allow_anonymous false
  • “allow_anonymous false” is used to prevent, clients without username and password to connecting to the broker.

5. Now start the broker with the following command,

mosquitto -c /etc/mosquitto/mosquitto.conf

6. If you need to verify the authentication, you can use following command, (you have to install mosquitto clients to do this)

mosquitto_sub -h localhost -p 1883 -t myTopic -u <user_name> -P <password>
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.