Search code examples
gomqttmosquittopaho

Cannot connect to mosquitto 2.0 with paho library


I cannot seem to connect to the mosquitto 2.0 broker from the paho library ("github.com/eclipse/paho.golang/paho") for golang. Can anyone point out the error of my ways?

I took the connect logic from the paho chat example and attempted to connect to my localhost server, but got reason code 135 (not authorised). I then attempted to connect to the mosquitto server with mosquitto_pub, with success. I used the same username and password for both cases. The mosquitto log output is below:

1608068903: New connection from 127.0.0.1:58794 on port 1883.
1608068903: Client <unknown> disconnected, not authorised.
1608069349: New connection from 127.0.0.1:58908 on port 1883.
1608069349: New client connected from 127.0.0.1:58908 as test (p5, c1, k60, u'username').

The mosquitto_pub command I'm using is:

snap run mosquitto.pub -h localhost -t hello -u username -P password -m hello -V mqttv5 -i test

The golang code is:

import (
    "context"
    "fmt"
    "github.com/eclipse/paho.golang/paho"
    log "github.com/sirupsen/logrus"
    "net"
)

func Test() {
    conn, err := net.Dial("tcp", "localhost:1883")
    if err != nil {
        log.Fatalf("Failed to connect to %s: %s", "localhost", err)
    }
    c := paho.NewClient(paho.ClientConfig{
        Router: paho.NewSingleHandlerRouter(func(m *paho.Publish) {
            log.Printf("%s : %s", m.Properties.User["chatname"], string(m.Payload))
        }),
        Conn: conn,
    })

    username := "username"
    password := "password"

    cp := &paho.Connect{
        KeepAlive:  30,
        ClientID:   "test",
        CleanStart: false,
        Username:   username,
        Password:   []byte(password),
    }
    ca, err := c.Connect(context.Background(), cp)
    if ca.ReasonCode != 0 {
        log.Fatalf("Failed to connect to %s : %d - %s", "localhost", ca.ReasonCode, ca.Properties.ReasonString)
    }
    if err != nil {
        log.Fatalln(err)
    }

    fmt.Printf("Connected to %s\n", "localhost")

}

Solution

  • Add UsernameFlag and PasswordFlag to paho.Connect e.g.:

    cp := &paho.Connect{
            KeepAlive:  30,
            ClientID:   "test",
            CleanStart: false,
            Username:   username,
            UsernameFlag: true,
            Password:   []byte(password),
            PasswordFlag: true,
        }
    

    The paho.golang documentation needs work but this is covered in the mqtt v5 spec. I have tested this with Mosquitto 2.0.1 and connected successfully.