shamblett / mqtt_client

A server and browser based MQTT client for dart
Other
547 stars 177 forks source link

How to connect mqtt with socket header options? #531

Closed sinhpn92 closed 2 months ago

sinhpn92 commented 5 months ago

Hello team,

I have a web client implemented using React.js to connect to my server. Now, I am developing a mobile app client with Flutter for the same purpose. I have reviewed some examples, but I haven't found a solution to connect to my server using socket header options. My server requires authentication in the header to verify the connection. Below is an example of how I implemented the connection on the React.js client:

const requestOptions = {
        clientId: "mqttclient",
        reschedulePings: false,
        reconnectPeriod: 2000,
        connectTimeout: 60000,
        protocolId: "6xm5cjX78OqX",
        protocolVersion: 3,
        wsOptions: {
            headers: {
                Authorization: "Bearer xxx",
                x-client-id: "iEtJGpzMTgyRe0x4m23lwdFA"
            },
            origin: "https://server.com",
            protocolVersion: 13,
        },
        clean: true,
        keepalive: 20,
        username: "admin",
    };
const client = new mqtt.Client(
        (_) => websocket('wss://...', requestOptions.wsOptions),
        requestOptions
    );

Does the mqtt_client package support this feature? Alternatively, do you have any suggestions on how to implement the connection with this option? Thank you for your assistance.

shamblett commented 5 months ago

No the client doesn't allow this, it only supports the setting of web protocols although server side web sockets in Dart do support this in the connect method -

static Future<WebSocket> connect(String url,
          {Iterable<String>? protocols,
          Map<String, dynamic>? headers,
          CompressionOptions compression =
              CompressionOptions.compressionDefault,
          HttpClient? customClient}) =>
      _WebSocketImpl.connect(url, protocols, headers,
          compression: compression, customClient: customClient);

This is a bit naughty really, the MQTT protocol doesn't support this kind of authentication, it has its own way of doing this.

The client can be updated to support this seeing as Dart supports it for future use, I'll mark this issue as an enhancement for now.

sinhpn92 commented 5 months ago

Thank you @shamblett for the supporting.

shamblett commented 2 months ago

Complete, see the websocketHeader API, package re released at version 10.4.0