When you connect a device to IoT Platform through an MQTT gateway, you can use a custom certificate to verify its identity and register it by using the Common Name (CN) from the certificate. This topic shows how to connect a device to IoT Platform by using third-party verification with Alibaba Cloud Function Compute (FC).
Important notes
The steps in this topic are performed as a regular user. If an operation requires administrative permissions, prefix the command with sudo.
Prerequisites
You have purchased an Exclusive Enterprise Edition instance. This topic uses an instance in the China (Shanghai) region as an example. For more information, see Purchase an Enterprise Edition instance.
Background information
IoT Platform provides an MQTT gateway feature that allows devices to connect and communicate. You can use features such as third-party verification with Function Compute, custom certificates, Online Certificate Status Protocol (OCSP), and custom communication topics for authentication to support various business scenarios.
For more information about device authentication and communication through an MQTT gateway, see MQTT gateway overview.
Preparations
This topic uses Ubuntu 22.04 as the development environment.
Step 1: Generate custom certificates
-
Log on to the Ubuntu operating system.
-
Run the following command to generate the root certificate
root-ca.crtfor both the device-side and server-side:openssl req \ -new \ -newkey rsa:2048 \ -days 365 \ -nodes \ -x509 \ -subj "/C=CN/O=Aliyun IOT/CN=IoT CA" \ -keyout root-ca.key \ -out root-ca.crt -
Generate a custom server-side certificate based on the
root-ca.crtroot certificate.-
Run the following command to generate the server-side key file
server.key:openssl genrsa -out server.key 2048 -
Run the
touch openssl.cnfcommand to create a file namedopenssl.cnf. -
Run the
vi openssl.cnfcommand. Then, add the following content to the file, press the Esc key, and enter:wqto save and exit.[policy_match] countryName = cn stateOrProvinceName = optional organizationName = optional organizationalUnitName = optional commonName = supplied emailAddress = optional [req] default_bits = 2048 distinguished_name = req_distinguished_name req_extensions = req_ext x509_extensions = v3_req prompt = no [req_distinguished_name] commonName = Server [req_ext] subjectAltName = @alt_names [v3_req] subjectAltName = @alt_names [alt_names] DNS.1 = *.mqtt.iothub.aliyuncs.com DNS.2 = *.igw.iothub.aliyuncs.com -
Run the following command to generate the server-side request file
server.csr:openssl req -new -key server.key -config openssl.cnf -out server.csr -
Run the following command to generate the server-side certificate file
server.crt:openssl x509 -req -days 365 -sha256 -in server.csr -CA root-ca.crt -CAkey root-ca.key -CAcreateserial -out server.crt -extensions v3_req -extfile openssl.cnf -
Run the following command to verify the server-side certificate:
openssl verify -CAfile root-ca.crt server.crt
-
-
Generate a custom device-side certificate based on the
root-ca.crtroot certificate.-
Run the following command to generate the device-side key file
client.key:openssl genrsa -out client.key 2048 -
Run the following command to generate the device-side certificate request file
client.csr. Set the CN toClient_123.openssl req -new -key client.key -out client.csr -subj "/CN=Client_123" -
Run the following command to generate the device-side certificate file
client.crt:openssl x509 -req -days 365 -sha256 -in client.csr -CA root-ca.crt -CAkey root-ca.key -CAcreateserial -out client.crt -
Run the following command to verify the device-side certificate:
openssl verify -CAfile root-ca.crt client.crt
-
Step 2: Create an FC function for authentication
-
In the top navigation bar, select the China (Shanghai) region. On the Services page, click Create Service.
-
In the Create Service panel, enter a Service Name, such as IoT_Service, and then click OK.
-
On the Functions page, click Create Function.
-
On the Create Function page, configure the following parameters and click Create.
Select Create with Built-in Runtime for the creation method. For Function Name, enter
three_party_auth. For Request Handler Type, select Event Handler. For Runtime, select Python 3.6. -
On the Function Details page, replace the sample code with the following code and click Deploy Code.
The authentication function returns the CN of the device certificate as the deviceName.
# -*- coding: utf-8 -*- import logging import json import time import enum import random import string class Request: def __init__(self, json_str): self.clientId = None self.username = None self.password = None self.certificateCommonName = None for key, value in json.loads(json_str).items(): setattr(self, key, value) class Response: def __init__(self): self.deviceName = None self.result = 'true' self.message = 'success' def handler(self, request): # Return the CN of the device certificate as the deviceName. self.deviceName = request.certificateCommonName return json.dumps(self.__dict__) def handler(event, context): request = Request(event) return Response().handler(request)
Step 3: Create a gateway
-
On the Instance Overview page, click your target Exclusive Enterprise Edition instance.
-
In the left-side navigation pane, choose Device Management > Gateway, and then click Add Gateway.
-
Configure the following parameters and click OK.
For Server Certificate, use the content of
server.crt. For Server Certificate Private Key, use the content ofserver.key. For Device Root Certificate, use the content ofroot-ca.crt. For more information about the parameters, see Add a gateway.For Protocol, select MQTT. For Custom Port, enter
1883. For Authentication Type, select Third-party Authentication. For Enable Data Passthrough, select No. For Enable Device X.509 Certificate Authentication, select No. For Enable OCSP, select Disabled. For Device Authentication FC Service, selectIoT_Service. For Device Authentication FC Function, selectthree_party_auth. For Authorization, selectAliyunIOTAccessingFCRole. -
In the gateway list, copy and save the Gateway URL.
Step 4: Develop the device-side program
-
Return to the Ubuntu operating system.
-
Run the following commands to install the required libraries:
sudo apt-get install build-essential gcc make cmake cmake-gui cmake-curses-gui sudo apt-get install libssl-dev -
Run the following commands to install the open source Paho MQTT library:
git clone https://github.com/eclipse/paho.mqtt.c.git mkdir build && cd build cmake ../paho.mqtt.c -DPAHO_WITH_SSL=TRUE -DCMAKE_INSTALL_PREFIX="/usr/lib" make -j sudo make install && cd .. -
Run the
touch aiot_mqtt_demo.ccommand to create a device simulator file namedaiot_mqtt_demo.c. -
Run the
vi aiot_mqtt_demo.ccommand to open the file and add the following content:#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "MQTTClient.h" int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message) { printf("message recv < topic [%s], payload [%s]\n", topicName, (char *)message->payload); MQTTClient_freeMessage(&message); MQTTClient_free(topicName); return 1; } int main(int argc, char* argv[]) { MQTTClient client; MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer; MQTTClient_SSLOptions ssl_opts = MQTTClient_SSLOptions_initializer; int rc; /* Create an MQTT client. Replace the placeholder values. */ const char *host = "ssl://iot-0****.igw.iothub.aliyuncs.com:1883"; const char *client_id = "12345"; MQTTClient_create(&client, host, client_id, MQTTCLIENT_PERSISTENCE_NONE, NULL); MQTTClient_setCallbacks(client, NULL, NULL, msgarrvd, NULL); /* Configure connection parameters: certificate, username, and password. Replace the placeholder values. */ ssl_opts.trustStore = "root-ca.crt"; ssl_opts.privateKey = "client.key"; ssl_opts.keyStore = "client.crt"; conn_opts.ssl = &ssl_opts; conn_opts.username = "sdk_test01"; conn_opts.password = "hello123"; /* Establish an MQTT connection. */ if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS) { printf("Failed to connect, return code %d\n", rc); exit(EXIT_FAILURE); } printf("connect success username %s, password %s\n", conn_opts.username, conn_opts.password); /* Subscribe to a topic. */ MQTTClient_subscribe(client, "/user/aiot_mqtt_demo_downraw", 1); /* Generate and publish messages in a loop. */ MQTTClient_message pubmsg = MQTTClient_message_initializer; const char *topic = "/user/aiot_mqtt_demo_upraw"; pubmsg.payload = "Hello Service!"; pubmsg.payloadlen = (int)strlen(pubmsg.payload); pubmsg.qos = 1; for(int i = 0; i < 100; i++) { MQTTClient_publishMessage(client, topic, &pubmsg, NULL); printf("message send > topic [%s], payload [%s]\n", topic, (char *)pubmsg.payload); sleep(10); } /* Disconnect and destroy the client. */ MQTTClient_disconnect(client, 10000); MQTTClient_destroy(&client); return rc; } -
In the code, modify the parameters based on your actual device information. Then, press the Esc key and enter
:wqto save theaiot_mqtt_demo.cfile.Parameter
Description
host
The MQTT gateway endpoint for device connection. The format is
ssl://${Gateway-Endpoint}:${Port-Number}.${Gateway-Endpoint}and${Port-Number}are the domain name and custom port from the Gateway URL that you obtained in Step 3.client_id
(Optional) The client ID. The ID must be a custom value of up to 64 characters. Use the device's MAC address or serial number (SN) for easier client identification.
ssl_opts.trustStore
The path to the device-side root certificate file
root-ca.crt.ssl_opts.privateKey
The path to the device-side key file
client.key.ssl_opts.keyStore
The path to the device-side certificate file
client.crt.conn_opts.username
The username for the MQTT connection.
The username must be 4 to 32 characters in length and can contain letters, digits, hyphens (-), underscores (_), at signs (@), periods (.), and colons (:). The username must be unique within the product.
conn_opts.password
The password for the MQTT connection.
The password must be 1 to 32 characters in length and can contain letters, digits, hyphens (-), underscores (_), at signs (@), periods (.), and colons (:).
After completing the preceding steps, your directory contains the following files:
build
paho.mqtt.c
aiot_mqtt_demo.c
client.crt
client.csr
client.key
openssl.cnf
root-ca.crt
root-ca.key
server.crt
server.csr
server.key
Step 5: Compile and run
-
Run the following commands to compile and run the device program file
aiot_mqtt_demo.c:gcc -o aiot_mqtt_demo aiot_mqtt_demo.c -lpaho-mqtt3cs ./aiot_mqtt_demoAfter the program runs successfully, the deviceName (
Client_123) returned by the FC authentication function is used as the DeviceName for the device in IoT Platform. A device namedClient_123is automatically created on the Device Management > Devices page of your instance in the IoT Platform console. The device status is Online. -
(Optional) To view data reported by the device, go to the IoT Platform console and view the Monitoring and Operations > Device Log page of your instance. Navigate to Monitoring and Operations > Device Log and click the Cloud Runtime Log tab. From the Product drop-down list, select the gateway product. In the Actions column, click View. In the View Details dialog box, verify that the Topic is
/user/aiot_mqtt_demo_uprawand the content isHello Service!. A status of 200 confirms that the message was successfully reported.