且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用具有Cognito身份验证的用户的Web套接字连接到AWS IoT

更新时间:2023-12-03 10:12:16

对于未经身份验证的认知身份,身份池已身份验证角色足以允许连接到IoT MQTT代理。但是,对于经过身份验证的认知身份,需要做两件事:

For unauthenticated cognito identities the "Identity pool anauthenticated" role is sufficient to allow connecting to the IoT MQTT broker. However for authenticated cognito identities two things are required:


  1. 身份池经过身份验证角色必须允许访问您的IoT操作要求(例如,连接,发布等)。

  1. The "Identity pool authenticated" role must allow access to the IoT actions you require (e.g. connect, publish etc).

您必须使用以下方法将IoT策略(与设备所附加的策略完全一样)附加到IoT身份: AttachPrincipalPolicy API

You must attach an IoT policy (exactly like the ones that are attached to your devices) to the cognito identity using the AttachPrincipalPolicy API

我今天早些时候遇到了第二步,因为在任何地方都不清楚这是什么。

Step 2 is where I was stuck earlier today as it was not particularly clear anywhere that this was required.

AFAIK无法将IoT策略从任何一个AWS网站附加到认知用户。但是,如果您在计算机上设置了AWS命令行界面,则可以从那里进行设置。该命令看起来像:

AFAIK there is no way to attach the IoT policy to a cognito user from any of the AWS web sites. However if you have the AWS command line interface setup on your machine you can do it from there. The command looks like:

aws iot attach-principal-policy --policy-name <iot-policy-name> --principal <cognito-identity-id>

可以使用 Federated Identities>找到认知身份ID。您的泳池>身份浏览器,或者您也可以在 CognitoIdentityCredentials.get 调用的响应中找到它。看起来像这样的 us-east-1:ba7cef62-f3eb-5be2-87e5-fffbdeed2824

The cognito identity id can be found using the Federated Identities > Your Pool > Identity browser or you could also find it in the responses to your CognitoIdentityCredentials.get call. It looks like this us-east-1:ba7cef62-f3eb-5be2-87e5-fffbdeed2824

用于生产系统中,您显然希望自动附加此策略,可能在用户注册时使用lambda函数。

For a production system you'll obviously want to automate attaching this policy, probably using a lambda function on user signup.

文档中有关需要附加IoT策略的部分可以在此页面

The section of the docs that talks about needing to attach the IoT policy can be found on this page:


要使经过身份验证的Amazon Cognito身份通过HTTP在您的AWS账户中的topic1上发布MQTT消息,您必须指定两个策略,如下所述。必须将第一个策略附加到Amazon Cognito身份池角色,并允许该池中的身份进行发布调用。第二个策略是使用AWS IoT AttachPrincipalPolicy API附加到Amazon Cognito用户的,并允许指定的Amazon Cognito用户访问topic1主题。

For an authenticated Amazon Cognito identity to publish MQTT messages over HTTP on topic1 in your AWS account, you must specify two policies, as outlined here. The first policy must be attached to an Amazon Cognito identity pool role and allow identities from that pool to make a publish call. The second policy is attached to an Amazon Cognito user using the AWS IoT AttachPrincipalPolicy API and allows the specified Amazon Cognito user access to the topic1 topic.