且构网

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

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

更新时间:2023-02-16 16:47:17

对于未经身份验证的认知身份,身份池经过身份验证"角色足以允许连接到 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).

您必须使用 AttachPrincipalPolicy API

今天早些时候我遇到了第 2 步,因为在任何地方都不是特别清楚需要这样做.

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

AFAIK 无法从任何 AWS 网站将 IoT 策略附加到认知用户.但是,如果您的机器上安装了 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.