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 Antwort
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
EXPERTE
beantwortet vor einem Jahr
  • In this way I created both IOT policy and IAM policy but it does not work. What else can I do?

Du bist nicht angemeldet. Anmelden um eine Antwort zu veröffentlichen.

Eine gute Antwort beantwortet die Frage klar, gibt konstruktives Feedback und fördert die berufliche Weiterentwicklung des Fragenstellers.

Richtlinien für die Beantwortung von Fragen