Shrouk Khan
Shrouk Khan

Reputation: 1460

Using AWS Services ( like IOT ) in regions without cognito

I am looking into using AWS IOT to let our hardwares communicate with user phones. We are using react-native-paho-mqtt library for this purpose.

I shall explain in short before the code:

  1. retrieve token from cognito federated identity in ap-northeast-1 ( tokyo ) , because cognito / federated identity is available there
  2. use that token to log into aws IOT in ap-southeast-1 ( singapore )
  3. fails with : Error: AMQJS0007E Socket error: Unknown socket error.

  4. the generated mqtt endpoint with sigV4 signing looks like this :

wss://a2mt3pd9aiue3c.iot.ap-southeast-1.amazonaws.com/mqtt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=ASIAIPXKPMB3YECA4IWQ/20170730/ap-northeast-1/iotdevicegateway/aws4_request&X-Amz-Date=20170730T132924Z&X-Amz-SignedHeaders=host&X-Amz-Signature=b67e19aa6a16703756b0fed6f60649e687ca2494ad23e0b28e0d6ba624b53fdb&X-Amz-Security-Token=yyy//////////bbb/xxx+PV2/YEn3Li8b/T7+hVm6v5HJBu6fSqiMFk8ReLIJYqRKb6dCVvKjow3ioGIVtTMs5dABg9rHmSH1Q4y1RZaje4pNjTakTbgb2uhnQ4AjNrlgb75WQxsckXEDr7QKy5+lWWO6C/tU3+kymk8KCBYBq1yoq5GOBlc9BdajwsrLOdDLozmIsaarqlSMQ/iS/SOoNmx7AK733hxUEU5ovaXKY5ffLRbJm+JqVxI+0zJP4Q4fHGX4f2qkQBUCzmLl454fKanmGk3yXoO0FH2jlcztoqGirvBAiP//////////8BEAAaDDUzODEwNjcxOTUxNSIMoUem00KSLGQAkZRxKsME5hnmdjdZVMQHgcc+gHRFraUqOwUJ0l4g/rUMzQVythsplcDOQ1gqFtAUiNm4Oy520ubgJylOHBSmzc+Zqjyd42Mh2a5kF1vj0FxwPpVJrzxEV1yRS6nLs6D6XMAaKZPrz0zMDriKI77LKyyBwtSBlI9ENILzYrGwe+i5K04TyYRJSZBszOZXtCVwDYQUJTwMzfNWY4R0UhyjC9/xxx+P/lWwxxA4FVVlWcc+xV8Fwjpem4/yl6eH0YmHhPrAAvQDAq+euBlbDJL5aV8czUQulowEJum6oVocngqP2W2zwid1fJT2C3xnVySZEHLrUZ7aULD6VswvzmKqmE9RBPE3+lPgsOKtGzw/BtdQYQmHsggqA8C7omwAzwUNAqa4/uVYGNdXUDUxytq9J2qFUeh74o0c/QsyUMcgsK/3hJySiMj+M7TuPTTAhCnf5WS3wL9dMjLsis88wGFbkUnOVS0N3hpFGLoIpc/EWy7hnbYZDJiLG9B02SiLtshZBc6D+somethingsomething+gVd7jdk0K6wMFwJ3Xc4tFoDzps13eszpMEfrMGGQSdKK7dFfwfMLO+98sF

the code fragment is this:

    fetch('https://xxx.execute-api.ap-northeast-1.amazonaws.com/dev/app/connect', { // retrieve app token from ap-northeast-1 cognito
     method: 'POST',
     headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    },
      body: JSON.stringify({"data": {"coreUserId": 100, "companyId": 1, 
      "brandId": 2, "hotelId": 3, "roomId": 4}})
     })
     .then((response) => response.json())
     .then((responseJson) => {

    console.warn("resnpose json is : ", responseJson)
    AWS.config.credentials = new AWS.CognitoIdentityCredentials({
      IdentityPoolId: AppConfig.identityPoolId,
      IdentityId: responseJson.message.cognitoIdentityId,
      Logins: {
        'cognito-identity.amazonaws.com': responseJson.message.token
      }
    });
    AWS.config.credentials.get((err) => {

      if (err) {
        console.error(err)
      }
      console.warn("AWS.config.credentials --> ", AWS.config.credentials)

      var ioturl = this.getSignedUrl(AppConfig.iotEndpoint, AppConfig.region, AWS.config.credentials);
      const client = new Client({
        uri: ioturl,
        clientId: AppConfig.credentials.cognitoIdentityId,
        storage: AsyncStorage
      });
      this.client = client;
      client.on('messageReceived', (message) => {
        try {
          const jsonResponse = JSON.parse(message.payloadString);
          console.warn(Date.now()," : received : ", jsonResponse);
        } catch (e) {
          console.warn("Failed to recieve: ", e)
        }
        //this.handleIoTMessage(jsonResponse);
      });

      client.on('connectionLost', (responseObject) => {
        console.warn('CLIENT DC');
        if (responseObject.errorCode !== 0) {
          //clearInterval(this.publishInterval);
          console.warn('CONNECTIONLOST TRIGGERED:', responseObject.errorMessage);
        }
      });

      var connectOptions = {
        useSSL: true,
        timeout: 30000, // In milliseconds, it turns out
        keepAliveInterval:30000,
        cleanSession:true,
        mqttVersion: 4,
      };
      AWS.config.update({region: "ap-southeast-1"}); //now try to connect to another region..where there is no cognito available
      const IoT = new AWS.Iot();


      var params = {
        policyName: "Test",
        principal: AppConfig.credentials.cognitoIdentityId // this cognito identity id is in ap-northeast-1 . NOT in ap-southeast-1 where IOT is located
      };

      IoT.attachPrincipalPolicy(params, (err) => {
        if (err) {
          console.error('ERROR attachPrincipalPolicy: ', err);
        }

        client.connect(connectOptions)
          .then((result) => {
            console.warn("connect resutl : ", result, " .. not subs ")
            return client.subscribe('b/2/p/3/r/4/#', {qos: 1, timeout: 15000})

          })
          .then(function (xx, yy) {
            console.warn("Subscribe succss : ", xx, yy)
            const message = new Message(JSON.stringify({"xxx": "yyy"}));
            message.destinationName = 'b/2/p/3/r/4/xx';
            return client.send(message);
          })
          .then(function (xx, yy) {
            return console.warn("Successfully sent : ", xx, yy)
          })

          .catch((responseObject) => {
            console.warn("response object is : ", responseObject);
            if (responseObject.errorCode !== 0) { // fail
              console.warn(`CATCH ONCONNECTIONLOSTTRIGGERED: ${responseObject.errorMessage}`);
            }
          });
      });
    });

  })
  .catch((error) => {
    console.error(error);
  });

And it fails with :

 Error: AMQJS0007E Socket error: Unknown socket error.

Can anyone suggest what needs to be done? Also what is the standard for authenticating users in regions without cognito ?

Upvotes: 1

Views: 355

Answers (1)

Vasileios Lekakis
Vasileios Lekakis

Reputation: 5572

Maybe you are aware of this already but Cognito launched in Singapore recently

Upvotes: 0

Related Questions