DEV Community

Fernando Tschopp
Fernando Tschopp

Posted on

MQTT Series: Authentication & Authorization

Authentication

Mosquitto 2.x is now more secure by default and requires users to make an active decision about how to configure security on their broker, rather than possibly relying on the previous very permissive behavior, as well as remove privileged access more quickly.

When Mosquitto is run without a configuration file, or without configuring any listeners, it will now bind to the 127.0.0.1 and/or ::1 loopback interfaces. This means that only connections from the local host will be possible.

Running the broker with a listener defined will by default bind to 0.0.0.0/:: and thus be accessible from any interface.

All listeners now default to allow_anonymous false unless explicitly set to true in the configuration file. This means that when configuring a listener, the user must configure an authentication and access control method, or set allow_anonymous to true.

Edit the configuration file

sudo nano /etc/mosquitto/mosquitto.conf 
Enter fullscreen mode Exit fullscreen mode

Edit the file adding the following content

# Setup listener port
listener 1883
# Set log type
log_type all
log_timestamp true
# Set the usser password file
password_file /etc/mosquitto/passwd
Enter fullscreen mode Exit fullscreen mode

Restart the service

sudo systemctl restart mosquitto
Enter fullscreen mode Exit fullscreen mode

Create MQTT users setting the password file defined before and replace mqtt-user1 for your desire username

sudo mosquitto_passwd -c /etc/mosquitto/passwd mqtt-user1
Enter fullscreen mode Exit fullscreen mode

Restart the service again

sudo systemctl restart mosquitto
Enter fullscreen mode Exit fullscreen mode

At this point you're ready to test the publish and subscribe commands.
In one terminal session run the following command:

mosquitto_sub -h <BROKER_IP> -t "mqtt/mytopic" -u mqtt-user1 -P password
Enter fullscreen mode Exit fullscreen mode

In other terminal session run the following command:

mosquitto_pub -h <BROKER_IP> -u mqtt-user1 -P password -t mqtt/mytopic -m "Hello World!"
Enter fullscreen mode Exit fullscreen mode

Authorization on Mosquitto Broker

The created users have access to all the topics, to limit the access permissions you have to configure the ACLs (Access Lists).
Create the ACLs file

sudo nano /etc/mosquitto/aclfile
Enter fullscreen mode Exit fullscreen mode

and put the following content

# This only affects clients with username 
user  mqtt-user1
topic readwrite #
topic read $SYS/#

user mqtt-user2
topic readwrite mytopic/#
topic read readponly/#

# This affects all clients.
pattern write $SYS/broker/connection/%c/state
Enter fullscreen mode Exit fullscreen mode

Edit the mosquitto configuration file

sudo nano /etc/mosquitto/mosquitto.conf
Enter fullscreen mode Exit fullscreen mode

and add the following line

acl_file /etc/mosquitto/aclfile

Restart the service

Top comments (0)