Can't log in to MQTT broker from Raspberry Pi using HA user

I am trying to set up paho-mqtt on a Raspberry Pi Zero 2W on my home network, to communicate with Home Assistant. I have already set up a MQTT broker on Home Assistant via Mosquitto.

The Python script I’m using to test connection looks like this:

  GNU nano 7.2                                                         pubSubPi.py                                                                  
# test_connect.py 
import paho.mqtt.client as mqtt 

# The callback function. It will be triggered when trying to connect to the MQTT broker
# client is the client instance connected this time
# userdata is users' information, usually empty. If it is needed, you can set it through user_data_set function.
# flags save the dictionary of broker response flag.
# rc is the response code.
# Generally, we only need to pay attention to whether the response code is 0.
def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("Connected success")
    else:
        print("Connected fail with code {rc}")

client = mqtt.Client() 
client.on_connect = on_connect 
# client.on_message = on_message
client.username_pw_set("[USER]", "[PASSWORD]")
client.connect("[LOCAL IP]", 1883, 60) 
client.loop_forever()

According to the Mosquitto add-on settings page, “you can use Home Assistant users too, without any configuration.” I have created a specific user (let’s call it mqtt) in Home Assistant for this purpose and restarted Home Assistant.

However, when I add the mqtt user’s login details to my Python script for the Raspberry Pi MQTT client and run the script, it fails to authorize. Mosquitto logs show:

...
2024-11-13 14:33:11: New connection from [IP] on port 1883.
2024-11-13 14:33:11: Client [clientname] disconnected, not authorised.
...

If I replace the login details with the username and password of my personal Home Assistant user and try again—having changed nothing else—then the login succeeds.

What am I missing? What is preventing me from logging into Mosquitto with one Home Assistant user, but not the other?

I changed the password for the “mqtt” user and it worked, so I wonder if my original password contained an invalid special character or something.