2017-07-31 2 views
0

Je suis en train d'étudier l'utilisation d'AWS IOT pour permettre à nos périphériques de communiquer avec les téléphones des utilisateurs. Nous utilisons la bibliothèque reac-native-paho-mqtt à cette fin.Utilisation des services AWS (comme IOT) dans les régions sans cognito

J'expliquerai en bref avant le code:

  1. récupérer jeton Cognito identité fédérée en ap-nord-1 (tokyo), parce que l'identité de Cognito/fédérée est disponible il
  2. utilisation ce jeton à se connecter à aws IOT dans ap-southeast-1 (singapour)
  3. échoue avec: Erreur: AMQJS0007E Erreur de socket: Erreur de socket inconnue.

  4. le point final de mqtt généré avec la signature sigV4 ressemble à ceci:

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

le fragment de code est le suivant:

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

Et il échoue avec:

Error: AMQJS0007E Socket error: Unknown socket error. 

Quelqu'un peut-il suggérer ce qui doit être fait? Aussi, quelle est la norme pour l'authentification des utilisateurs dans les régions sans cognito?

Répondre

0

Peut-être que vous êtes déjà au courant de cela, mais Cognito a lancé en Singapore recently