I have an IoT React application that uses Cognito for federated authentication, and AWS IoT Core as the IoT broker. I am using Amplify and mqtt libraries in the project.

I need to create a signed url to connect to the broker.

I am doing this like so:

import { MqttClient, connect } from 'mqtt'
import { API, Auth, Signer } from 'aws-amplify'
...
const {accessKeyId, secretAccessKey,sessionToken} = await Auth.currentCredentials()
const signedUrl = generateSignedUrl({accessKeyId, secretAccessKey, sessionToken})

connect(signedUrl , {
...
transformWsUrl: () => generateSignedUrl({accessKeyId, secretAccessKey, sessionToken})
})
...

function generateSignedUrl({accessKeyId, secretAccessKey, sessionToken}) {
...
return Signer.signUrl(
    endpoint,
    {
      access_key: accessKeyId,
      secret_key: secretAccessKey,
      session_token: sessionToken
    },
    serviceInfo
  )
}

This works initially. But eventually (especially on mobile if the tab is inactive for 1+ hours), I get a 403 error when I try to reconnect to my mqtt broker. I am guessing this is because I now have a new session token, but am still passing the old one to generateSignedUrl(). However, since transformWsUrl() does not accept Promises, I don't know where to retrieve the new tokens to pass to generateSignedUrl().

How can I pass updated tokens to transformWsUrl() once they have been renewed in this case?

Thanks.

0

There are 0 best solutions below