Search code examples
reactjsamazon-web-servicesmqttaws-iot

React & AWS IoT MQTT over WSS - "connection lost - will attempt reconnection in x seconds"


I am unable to successfully connect to an AWS IoT device via MQTT using websockets with authenticated cognito users. I am using aws-iot-device-sdk in a react application. Upon trying to connect, the following debug logs get printed to the web browser console:

canonical request: GET
/mqtt
X-Amz-Algorithm=<removed>
SignedHeaders=host
host:<removed>.iot.us-east-1.amazonaws.com

host
<removed>

index.js:102 hashed canonical request: <removed>

index.js:111 string to sign: <removed>
<removed>
20210618/us-east-1/<removed>

index.js:117 signing key: <removed>

index.js:125 signature: <removed>

index.js:137 url: wss://<removed>.iot.us-east-1.amazonaws.com/mqtt?X-Amz-Algorithm=<removed>
index.js:630 using websockets, will connect to 'wss://<removed>.iot.us-east-1.amazonaws.com/mqtt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=....
index.js:781 connection lost - will attempt reconnection in 128 seconds...

JS Code To Create the Device and Connect:

var device = awsIot.device({
    clientId     : <unique client id>,
    region       : 'us-east-1',
    debug        : true,
    host         : '<removed>.iot.us-east-1.amazonaws.com',
    protocol     : 'wss',
    accessKeyId  : accessKeyId,
    secretKey    : secretAccessKey,
    sessionToken : sessionToken
});

device.on('connect', function(err, data) {
    if (err) {
        console.log(`Connection Error: ${err}`);
        return;
    }
    console.log('connected');
})

Authenticated IoT AWS Roles:

"Action": [
                "iot:Connect",
                "iot:Subscribe",
                "iot:Publish",
                "iot:Receive"
            ],
            "Resource": [
                "arn:aws:iot:us-east-1:<removed>:client/cognito_user_*",
                "arn:aws:iot:us-east-1:<removed>:topic*/resource/*"
            ]

I am able to connect to the MQTT broker using certs with MQTT.fx but the application I am working on requires authenticated cognito users to be able connect to the broker. Any insight would be appreciated.


Solution

  • Solved this problem.

    The problem I was having was the Cognito User did not have a necessary certificate associated with it in order to access the resource.