在没有cognito的地区使用AWS服务(如IOT)

时间:2017-07-31 01:54:32

标签: amazon-web-services mqtt amazon-cognito paho aws-iot

我正在研究使用AWS IOT让我们的硬件与用户手机通信。我们正在使用react-native-paho-mqtt库来实现此目的。

我将在代码之前简要解释一下:

  1. 从ap-northeast-1(东京)的Cognito联合身份中检索令牌,因为那里有认知/联合身份
  2. 使用该令牌登录ap-southeast-1(新加坡)的aws IOT
  3. 失败并出现:错误:AMQJS0007E套接字错误:未知套接字错误。

  4. 使用sigV4签名生成的mqtt端点如下所示:

  5.   

    WSS://a2mt3pd9aiue3c.iot.ap-southeast-1.amazonaws.com/mqtt X-AMZ-算法= AWS4-HMAC-SHA256&安培; X-AMZ-凭证= ASIAIPXKPMB3YECA4IWQ / 20170730 / AP-东北-1 / iotdevicegateway / aws4_request&安培; X-AMZ-日期= 20170730T132924Z&安培; X-AMZ-SignedHeaders =宿主安培; X-AMZ-签名= b67e19aa6a16703756b0fed6f60649e687ca2494ad23e0b28e0d6ba624b53fdb&安培; X-AMZ-安全令牌= YYY ////////// BBB / XXX + PV2 / YEn3Li8b / T7 + hVm6v5HJBu6fSqiMFk8ReLIJYqRKb6dCVvKjow3ioGIVtTMs5dABg9rHmSH1Q4y1RZaje4pNjTakTbgb2uhnQ4AjNrlgb75WQxsckXEDr7QKy5 + lWWO6C / TU3 + kymk8KCBYBq1yoq5GOBlc9BdajwsrLOdDLozmIsaarqlSMQ / IS / SOoNmx7AK733hxUEU5ovaXKY5ffLRbJm + JqVxI + 0zJP4Q4fHGX4f2qkQBUCzmLl454fKanmGk3yXoO0FH2jlcztoqGirvBAiP ////////// 8BEAAaDDUzODEwNjcxOTUxNSIMoUem00KSLGQAkZRxKsME5hnmdjdZVMQHgcc + gHRFraUqOwUJ0l4g / rUMzQVythsplcDOQ1gqFtAUiNm4Oy520ubgJylOHBSmzc + Zqjyd42Mh2a5kF1vj0FxwPpVJrzxEV1yRS6nLs6D6XMAaKZPrz0zMDriKI77LKyyBwtSBlI9ENILzYrGwe + i5K04TyYRJSZBszOZXtCVwDYQUJTwMzfNWY4R0UhyjC9 / XXX + P / lWwxxA4FVVlWcc + xV8Fwjpem4 / yl6eH0YmHhPrAAvQDAq + euBlbDJL5aV8czUQ ulowEJum6oVocngqP2W2zwid1fJT2C3xnVySZEHLrUZ7aULD6VswvzmKqmE9RBPE3 + lPgsOKtGzw / BtdQYQmHsggqA8C7omwAzwUNAqa4 / uVYGNdXUDUxytq9J2qFUeh74o0c / QsyUMcgsK / 3hJySiMj + M7TuPTTAhCnf5WS3wL9dMjLsis88wGFbkUnOVS0N3hpFGLoIpc / EWy7hnbYZDJiLG9B02SiLtshZBc6D + somethingsomething + gVd7jdk0K6wMFwJ3Xc4tFoDzps13eszpMEfrMGGQSdKK7dFfwfMLO + 98sF

    代码片段是这样的:

        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);
      });
    

    它失败了:

     Error: AMQJS0007E Socket error: Unknown socket error.
    

    有人可以建议需要做什么吗?在没有cognito的地区验证用户的标准是什么?

1 个答案:

答案 0 :(得分:0)

也许您已经意识到这一点,但Cognito在Singapore recently

中推出