AWS IoT Core and Cognito User/Identity Pools Connection

0

Hello,

I am sending data to aws iot core with mqtt. I used to use X.509 certificate file to connect to AWS IoT Core MQTT but now I want to use cognito instead of this certificate. I want users in Cognito to only send user1 to topic1 and user2 to topic2. How can I set this? How do I connect iot core to cognito? Should I create a policy in IAM or an Iot policy? How can I write the required policy for this?

In this case, how is write the python code that I send the data to iot core using Cognito? The previous code is as follows (code when I use iot X.509 certificate file) ;

import json
import random
import AWSIoTPythonSDK.MQTTLib as AWSIoTPyMQTT

# AWSIoTMQTTClient connection configuration
ENDPOINT = "iot-endpoint"
PATH_TO_CERT = "certificate.pem.crt"
PATH_TO_KEY = "private.pem.key"
PATH_TO_ROOT = "AmazonRootCA1.pem"
CLIENT_ID = 'client_id'
PORT = 8883
TOPIC = test/topic1
myAWSIoTMQTTClient = AWSIoTPyMQTT.AWSIoTMQTTClient(CLIENT_ID)
myAWSIoTMQTTClient.configureEndpoint(ENDPOINT, PORT)
myAWSIoTMQTTClient.configureCredentials(PATH_TO_ROOT, PATH_TO_KEY, PATH_TO_CERT)
myAWSIoTMQTTClient.connect()
print('Begin Publish')

while True:
   random_number = random.randint(1, 100)
   data = {'id': 1, 'value': random_number}
    # Publish to AWS
    myAWSIoTMQTTClient.publish(TOPIC, json.dumps(data), 1)
    print(f"Published:  {json.dumps(data)} to the topic:  {TOPIC}")

print('Publish End')
myAWSIoTMQTTClient.disconnect()

How am I supposed to write the code when I use Cognito? Which python library can I use?

Can you help me with this?

1 回答
0

Hi.

You can limit the Topic a user can subscribe/publish to using the variable cognito-identity.amazonaws.com:sub in the IoT Core policy. Something like this.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "iot:Connect"
            ],
            "Resource": [
                "arn:aws:iot:<REGION>:<ACCOUNT_ID>:client/${cognito-identity.amazonaws.com:sub}"
            ],
            "Effect": "Allow"
        }
}

To connect you use temporary IAM credentials retrieved via the identity pool.

See AWS Documentation and this blog example

profile picture
专家
已回答 10 个月前
  • In this way I created both IOT policy and IAM policy but it does not work. What else can I do?

您未登录。 登录 发布回答。

一个好的回答可以清楚地解答问题和提供建设性反馈,并能促进提问者的职业发展。

回答问题的准则