使用cognito凭证注册aws iot设备

时间:2017-11-22 11:48:32

标签: aws-sdk aws-cognito aws-iot

我正在开发一个应用程序,我需要跟踪某些设备的更改并在前端显示这些设备。

对于用户登录我使用cognito并且我在登录后获取凭证并且我已经获得了有效的凭证,因为我使用相同的凭证连接了AWS DynamoDB。

现在我想注册一个具有相同认证凭证的aws.iot设备。

我跟随https://github.com/aws/aws-iot-device-sdk-js

我使用aws用户检查了一些静态凭证,如:

client.device = awsIot.device({
    clientId: clientID,
    host: host,
    accessKeyId: AccessKeyId,
    secretKey: secretKey,
    protocol: 'wss'
});

这很好用。

然后我尝试使用aws cognito assessmentKeyId和secretKey,但是这次我得到了403.

我查了connect to AWS IoT using web socket with Cognito authenticated users,但没有帮助。

我目前的代码如下:

    var awsIot = require('aws-iot-device-sdk');

    AWS.config.credentials.get(() => {
        const IoT = new AWS.Iot();
        IoT.attachPrincipalPolicy({
            policyName: 'PubSub',
            principal: AWS.config.credentials.identityId
        }, (err, res) => {
            if (err) {
            } else {
                let credential;
                if (AWS.config.credentials && AWS.config.credentials.data && AWS.config.credentials.data.Credentials) {
                    let credentials = AWS.config.credentials.data.Credentials;
                    awsIot.device({
                       clientId: clientID,
                       host: host,
                       accessKeyId: credentials.AccessKeyId,
                       secretKey: credentials.secretKey,
                       protocol: 'wss',
                       sessionToken: credentials.SessionToken
                    });
                }
            }
        });
    });

任何人都可以帮助我,我在这里失踪了。

1 个答案:

答案 0 :(得分:2)

对我有用的是直接从AWS.config.credentials对象传递数据,即

if (AWS.config.credentials) {
  awsIot.device({
     clientId: clientID,
     host: host,
     accessKeyId: AWS.config.credentials.accessKeyId,
     secretKey: AWS.config.credentials.secretAccessKey,
     protocol: 'wss',
     sessionToken: AWS.config.credentials.sessionToken
  });
}

如果您通过此方法调用,也可以检查accessKeyId等以小写字母开头而不是大写字母。

相关问题