【问题标题】:AWS IoT Core: Can not use Mqtt to connect with Cognito identityAWS IoT Core:无法使用 Mqtt 连接 Cognito 身份
【发布时间】:2021-01-09 17:12:08
【问题描述】:

应用是由angular制作的。

首先,用户应该使用 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 "&lt;&lt; MY-IOT-POLICY &gt;&gt;" --principal "&lt;&lt; MY-COGNITO-IDENTITY-ID &gt;&gt;"

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

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

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

【问题讨论】:

    标签: angular mqtt amazon-cognito aws-iot


    【解决方案1】:

    我在 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/*"
        }
      ]
    }
    

    【讨论】:

    • 请注意,与 AWS 的最小权限原则相比,您新定义的策略过于宽松
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-13
    • 2018-03-02
    • 2022-12-07
    • 2020-12-01
    • 2017-03-11
    • 2019-09-15
    • 2019-02-11
    相关资源
    最近更新 更多