1 introduction

The AWS IoT solution is a fully hosted cloud platform that enables connected devices to easily and securely interact with cloud applications and other devices. AWS IoT can support billions of devices and trillions of messages that can be processed and routed securely and reliably to AWS end nodes and other devices.

The AWS IoT platform allows you to connect devices to AWS services and other devices, secure data and interactions, process device data and perform actions on it, and enable applications to interact with devices even when they are offline.

The first step in using AWS IoT is to connect the device to the AWS IoT Core service. AWS IoT supports multiple access protocols, authentication methods, and authorization policies.

2 protocols supported by AWS IoT

To access AWS IoT, a device must first interact with the IoT platform using the protocols supported by AWS IoT.

2.1 the HTTP protocol

The HTTP protocol is the most common protocol in the Internet. The HTTP protocol supports all of the authentication and authorization modes mentioned later. However, in the scenario of the Internet of Things, it is also determined by large protocol overhead, etc. In addition, the mode of HTTP only request and response does not support the subscription mode, which is very important in the scenario of the Internet of Things, and cannot support the issuing of downlink commands.

2.2 the MQTT protocol

MQTT protocol is the most widely used protocol in the Internet of Things scenario. It has the advantages of low protocol overhead and supporting all modes such as publish and subscribe.

2.3 the MQTT over WEBSOCKET

MQTT over WebSocket is based on the MQTT protocol over websockets, which uses port 443 and has advantages over MQTT in terms of network environment accessibility, but is also relatively complex.

3 Authentication and authorization methods supported by AWS IoT

When a device is connected to AWS IoT, it must be authenticated to verify the device’s legal identity. Once authenticated, requests for devices need to be authenticated, and only authorized requests are accepted by AWS IoT. Different equipment authentication methods may have different authorization methods.

There are four types of authentication supported by AWS IoT, which are IAM Identity, Cognito Identity, X.509 Certificates, and Custom Authentication.

AWS IoT supports two kinds of pre-sales policies, namely IAM Policy and IoT Policy.

authentication The authorization policy Supported protocols Usage scenarios
IAM identity IAM policy http/mqtt over websocket Informal scene
Amazon cognito identity IAM policy/IoT policy http/mqtt over websocket The mobile terminal
X. 509 certificate IoT policy http/mqtt The default option
Custom authentication IoT policy http/mqtt over websocket Special scenario

4 Preparation

4.1 Create the operating environment

Create an EC2 server on AWS, and during the creation process, you need to create a role to access the EC2

Click “Create a new IAM character”

Click “Create Character”

Select “AWS Product” -> “EC2” and click “Next”

Select “AdministratorAccess”, click “Next”, the label section can be ignored, click “Next”

Enter the specified role name, “Create a role”, and then go back to the interface where EC2 was created and refresh the role

Then continue the EC2 configuration until the creation is successful (detailed steps are outlined).

4.2 Configure the operating environment

Login remotely to the EC2 server you created (the details are brief)

Because the operation is carried out through AWS CLI, and I created EC2 does not have the CLI installed, so I need to install it myself. Installation steps see https://docs.aws.amazon.com/zh_cn/cli/latest/userguide/install-linux.html#install-linux-awscli, omit specific installation process, It may take a lot of trial and error, with slightly different versions of the operating system, but see for yourself. Finally, the CLI was successfully installed, as shown below:

To configure the AWS CLI, I choose the region of the East Virginia, so fill in US-East-1, and the output format is usually JSON.

To prepare the action directory, now create a new action directory, AWSIotAccessDemo.

Then download the Root CA certificate for the AWS IoT. The ATS endpoint should be preferred for device connection, using the ATS CA file, because the custom authentication that follows does not support ATS endpoints for the time being, so you also need to download the VeriSign endpoint CA certificate. Execute the command wget HTTP: / / https://www.amazontrust.com/repository/AmazonRootCA1.pem

Execute the command wget again https://www.symantec.com/content/en/us/enterprise/verisign/roots/VeriSign-Class%203-Public-Primary-Certification-Authori ty-G5.pem

Install the dependent packages and execute the following command

sudo yum install python-pip jq -y
pip install boto3 --user
pip install AWSIoTPythonSDK --user
pip install flask --user
pip install paho-mqtt --user

And then obtain the Account Id, execute the command account_id = aws STS get – caller identity – | jq. Account | sed ‘s/” / / g’

Get the Account’s IoT Endpoint prefix, Execute the command ` endpoint_prefix = aws iot describe – the endpoint \ | jq. The endpointAddress | sed ‘s/” / / g’ | awk – f. ‘{print $1}’ `

Configure the newly obtained Account ID and Endpoint prefix into the environment variable and execute the following command:

echo "export account_id=$account_id" >> ~/.bashrc
echo "export endpoint_prefix=$endpoint_prefix" >> ~/.bashrc

4.3 Configure IoT message reception monitoring page

Log in to the AWS IoT console, click on the “Test” entry, and enter the subscription topic “IOTDEMO /#”.

Click “Subscribe to Topics” and all subsequent IOT Core messages will be displayed below.

5 Access using IAM authentication

The AWS supported methods of device access authentication have been listed earlier, and in this article we will try to access them with different authentication methods.

The user can authenticate the device by providing an identity using IAM. The device needs to preset or otherwise obtain the Security Credential and sign the request using SIGV4’s signature algorithm. The AWS IoT service authenticates the identity of the device through the signature. Once the identity is authenticated, the IoT then authenticates the request according to the IAM Policy owned by the identity.

The schematic diagram of IAM identity authentication is as follows:

5.1 Create an IAM user, IotDeviceUser

Enter the command AWS iAM create-user –user-name IoTDeviceUser

Create the AccessKey for the IOTDeviceUser user

Type the command ‘AWS iAM create-access-key \

--user-name IoTDeviceUser > /tmp/IoT_demo_access_key`

Record the accessKeyID and secretaccessKey and enter the following command:

AccessKeyId=cat /tmp/IoT_demo_access_key| jq .AccessKey.AccessKeyId| sed 's/"//g'
SecretAccessKey=cat /tmp/IoT_demo_access_key| jq .AccessKey.SecretAccessKey| sed 's/"//g'

Log on to the IAM console to see the IAM user you just created

As you can see from the figure above, the IotDeviceUser user has been created successfully, but no policy has been specified. In fact, IAM user creation and policy operations can be carried out in the console, and more convenient, the previous use of CLI is just to experience the operation.

5.2 The device is accessed using HTTP protocol

1) Create the IAM Policy for the device, enter the command:

device_IAM_http_policy_arn=aws iam create-policy \
--policy-name IoTDeviceIAMHttpPolicy \
--policy-document "{
    \"Version\": \"2012-10-17\",
    \"Statement\": [
        {
            \"Sid\": \"VisualEditor0\",
            \"Effect\": \"Allow\",
            \"Action\": \"iot:Publish\",
            \"Resource\": [
                \"arn:aws:iot:us-east-1:${account_id}:topic/IoTDemo/device_IAM_http\"
            ]
        }
    ]
}" | jq .Policy.Arn | sed 's/"//g'

2) Bind the IAM Policy to the IAM user and execute the command

aws iam attach-user-policy --user-name IoTDeviceUser \
--policy-arn ${device_IAM_http_policy_arn}

Bind the IAM Policy to the IAM user and execute the command

 aws iam attach-user-policy --user-name IoTDeviceUser \
--policy-arn ${device_IAM_http_policy_arn}

3) Generate the simulation device program and execute the following commands:

cat <<-EOF > ~/awsIoTAccessDemo/device_IAM_http.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import boto3
import argparse
import json
#获取参数

parser = argparse.ArgumentParser(description='Send data to IoT Core')
parser.add_argument('--data', default="data from device_IAM_http",
            help='data to IoT core topic')
parser.add_argument('--AccessKeyId', required=True,
            help='AccessKeyId')
parser.add_argument('--SecretAccessKey', required=True,
            help='SecretAccessKey')

args = parser.parse_args()
data = args.data
access_key_id = args.AccessKeyId
secret_access_key = args.SecretAccessKey

device_name = 'device_IAM_http'
region = 'us-east-1'
topic = "IoTDemo/"+device_name

iot_data_client = boto3.client('iot-data',region_name=region,aws_access_key_id=access_key_id,aws_secret_access_key=secret_access_key)

response = iot_data_client.publish(
    topic=topic,
    qos=0,
    payload=json.dumps({"source":device_name, "data":data})
)
EOF

Note: The areas in the code should be filled in correctly.

4) Run the simulation equipment program

python device_IAM_http.py --data "data from device IAM http." \
--AccessKeyId ${AccessKeyId} --SecretAccessKey ${SecretAccessKey}

5) Go to the IoT console to check the received message

As can be seen from the above figure, the message came from the.py file just created, and the content of the message was also the fields in the file, thus proving that the device sent the message successfully. In the future, I will continue to try to access with different identity authentication and different protocols.

Reference: https://amazonaws-china.com/cn/blogs/china/connect-your-devices-to-aws-iot-securely-1/?nc1=b_rp



Look at the original