AWS IoT Core:无法使用Mqtt与Cognito身份连接

时间:2020-09-23 13:23:12

标签: angular mqtt amazon-cognito aws-iot

应用程序是按角度进行的。

首先,用户应使用Cognito登录。因此,在用户登录后,应用程序将获取CognitoUser数据,例如其ID令牌,访问的密钥和会话令牌。

然后,应用程序将开始连接到Iot Core,并尝试将数据订阅或发布到我想要的主题。但是我总是遇到Mqtt立即断开连接的情况。

以下是我的连接代码:

export class MqttService{
  private awsIot: any;
  private iotDevice: any;
  public sendMessageSubject = new Subject<any>();
  public receiveMessageSubject = new Subject<string>();

  constructor(private authService: AuthService, private router: Router) { 
    this.awsIot = require('aws-iot-device-sdk');
    AWS.config.region = 'us-east-2';

    this.authService.getUserPool.getCurrentUser().getSession(function(err, session) {
      if (err) {
        console.log(err);
        return;
      } else if(session.isValid()) {
        this.initMqtt(session.getIdToken().getJwtToken());
      }
    });
  }

  public sendMesssage(value: string): Observable<boolean> {
    const topic = 'topic/topic1';
    const res = this.iotDevice.publish(topic, JSON.stringify({'message': value}));

    this.sendMessageSubject.next(res);
  }

  private initMqtt(idToken: string) {
    AWS.config.credentials = new AWS.CognitoIdentityCredentials({
      IdentityPoolId: '<< IDENTITY-POOL-ID >>',
      Logins: {
          'cognito-idp.us-east-2.amazonaws.com/us-east-2_XXXXXXXXX': idToken
      }
    });

    (<AWS.CognitoIdentityCredentials> AWS.config.credentials).refresh((error) => {
      if (error) {
        console.log(error);
      } else {
        console.log('success');
        const deviceOptions = {
          clientId: '<< CLIENT-ID >>',
          host: 'XXXXXXXXXXXXXX-ats.iot.us-east-2.amazonaws.com',
          protocol: 'wss',
          port: 443,
          accessKeyId: AWS.config.credentials.accessKeyId,
          secretKey: AWS.config.credentials.secretAccessKey,
          sessionToken: AWS.config.credentials.sessionToken,
          reconnectPeriod: 0
        }

        this.iotDevice = this.awsIot.device(deviceOptions);

        this.iotDevice.on('error', (err) => {
          console.log('MQTT Error');
        });
  
        this.iotDevice.on('connect', (result) => {
          /* It is always triggered here, then go to 'close' scope */
          console.log('MQTT connected');
          this.iotDevice.subscribe('topic/topic1');
        });
  
        this.iotDevice.on('reconnect', () => {
          console.log('MQTT reconnect');
        });
  
        this.iotDevice.on('close', () => {
          /* It is always triggered immediately after trigger 'connect' */
          this.iotDevice.end();
          console.log('MQTT Disconnected');
        });
  
        this.iotDevice.on('message', (sourceTopic: string, payload: any) => {
          console.log('Message Received from topic:' + sourceTopic);
          console.log('Message content:' + payload.toString());
          this.receiveMessageSubject.next(payload.toString());
        });
      }
    });
  }
}

在运行代码之前,我还要运行以下命令:

aws iot attach-principal-policy --policy-name "<< MY-IOT-POLICY >>" --principal "<< MY-COGNITO-IDENTITY-ID >>"

我还将Iot策略附加到身份验证角色上。

我认为主要的问题出在'cognito-idp.us-east-2.amazonaws.com/us-east-2_XXXXXXXXX': idToken,但我不确定。

如果有人知道,请告诉我。谢谢!

1 个答案:

答案 0 :(得分:0)

我修改了Iot Core中的策略,现在可以正常使用了。

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "iot:*",
      "Resource": "*"
    }
  ]
}

原文:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "iot:Connect",
      "Resource": "arn:aws:iot:us-east-2:xxxxxxxxxxxx:client/<< CLIENT-ID >>"
    },
    {
      "Effect": "Allow",
      "Action": "iot:Publish",
      "Resource": "arn:aws:iot:us-east-2:xxxxxxxxxxxx:topic/topoc1/*"
    },
    {
      "Effect": "Allow",
      "Action": "iot:Subscribe",
      "Resource": "arn:aws:iot:us-east-2:xxxxxxxxxxxx:topic/topic1/*"
    }
  ]
}