×
Community Blog Using HTTPS to Access IoT Platform from a Device

Using HTTPS to Access IoT Platform from a Device

This article describes how to access the IoT Platform using HTTPS. It explains the complete process through a Node.js case study.

HTTPS Access to IoT Platform from a Device

The IoT platform supports HTTPS access from a device only in China (Shanghai). For more information on the access flow for communication using HTTP connections refer to this document.

1) Device Authentication: Token Acquisition Based on Trituple Information

To begin with, view the HTTPS server endpoint.

1

2

Consider the following sample authentication request.

POST /auth HTTP/1.1
Host: iot-as-http.cn-shanghai.aliyuncs.com
Content-Type: application/json
body: {
    "version": "default",
    "clientId": "mylight1000002",
    "signmethod": "hmacsha1",
    "sign": "4870141D4067227128CBB4377906C3731CAC221C",
    "productKey": "ZG1EvTEa7NN",
    "deviceName": "NlwaSPXsCpTQuh8FxBGH",
    "timestamp": "1501668289957"
}

The following snippet shows the sample response.

{
  "code": 0,//业务状态码
  "message": "success",//业务信息
  "info": {
    "token":  "6944e5bfb92e4d4ea3918d1eda3942f6"
  }
}

2) Device Data Reporting

The HTTPS server endpoint is at https://iot-as-http.cn-shanghai.aliyuncs.com/topic/${topic}.

3

Consider the following sample request.

POST /topic/a1GFjLP3xxC/device123/pub
Host: iot-as-http.cn-shanghai.aliyuncs.com
password:${token}
Content-Type: application/octet-stream
body: ${your_data}

The preceding sample request shows the following response.

{
  "code": 0,//业务状态码
  "message": "success",//业务信息
  "info": {
    "messageId": 892687627916247040
  }
}

3) Node.js Case Study

Let's take a quick look at the case study for Node.js. The following sections describe the various steps.

3.1 Create an Advanced Product

Refer to the following snapshot to create an advanced product.

4

3.2 Define Functions

Next, add product property definitions as listed in the following table.

Property Identifier Data type Valid value
Temperature temperature FLOAT -50 to 100
Humidity humidity FLOAT 0 to 100

5

3.3 Register a Device and Obtain Identity Trituple Information on the Devices Page

Obtain identity trituple information on the device page post registering a device as shown below.

6

3.4 Run Device Simulation Code

Now, execute the following device simulation code.

var rp = require('request-promise');
const crypto = require('crypto');

const deviceConfig = {
    productKey: "替换productKey",
    deviceName: "替换deviceName",
    deviceSecret: "替换deviceSecret"
}

const topic = `/sys/${deviceConfig.productKey}/${deviceConfig.deviceName}/thing/event/property/post`;

//1.获取身份token
rp(getAuthOptions(deviceConfig))
    .then(function(parsedBody) {
        console.log('Auth Info :'+JSON.stringify(parsedBody))
        //2.发布物模型数据
        pubData(topic, parsedBody.info.token, getPostData())
    })
    .catch(function(err) {
        console.log('Auth err :'+JSON.stringify(err))
    });

//生成Auth认证的参数
function getAuthOptions(deviceConfig) {

    const params = {
        productKey: deviceConfig.productKey,
        deviceName: deviceConfig.deviceName,
        timestamp: Date.now(),
        clientId: Math.random().toString(36).substr(2),
    }

    //1.生成clientId,username,password
    var password = signHmacSha1(params, deviceConfig.deviceSecret);

    var options = {
        method: 'POST',
        uri: 'https://iot-as-http.cn-shanghai.aliyuncs.com/auth',
        body: {
            "version": "default",
            "clientId": params.clientId,
            "signmethod": "hmacsha1",
            "sign": password,
            "productKey": deviceConfig.productKey,
            "deviceName": deviceConfig.deviceName,
            "timestamp": params.timestamp
        },
        json: true
    };

    return options;
}

//publish Data to IoT
function pubData(topic, token, data) {

    const options = {
        method: 'POST',
        uri: 'https://iot-as-http.cn-shanghai.aliyuncs.com/topic' + topic,
        body: data,
        headers: {
            password: token,
            'Content-Type': 'application/octet-stream'
        }
    }

    rp(options)
        .then(function(parsedBody) {
            console.log('publish success :' + parsedBody)
        })
        .catch(function(err) {
            console.log('publish err ' + JSON.stringify(err))
        });

}
//模拟物模型数据
function getPostData() {
    var payloadJson = {
        id: Date.now(),
        params: {
            humidity: Math.floor((Math.random() * 20) + 60),
            temperature: Math.floor((Math.random() * 20) + 10)
        },
        method: "thing.event.property.post"
    }

    console.log("===postData\n topic=" + topic)
    console.log(payloadJson)

    return JSON.stringify(payloadJson);
}
//HmacSha1 sign
function signHmacSha1(params, deviceSecret) {

    let keys = Object.keys(params).sort();
    // 按字典序排序
    keys = keys.sort();
    const list = [];
    keys.map((key) => {
        list.push(`${key}${params[key]}`);
    });
    const contentStr = list.join('');
    return crypto.createHmac('sha1', deviceSecret).update(contentStr).digest('hex');
}

3.5 View Code Execution Results

Once the preceding code successfully executes, navigate to the following screen to finally view the results.

7

0 0 0
Share on

GXIC

25 posts | 3 followers

You may also like

Comments

GXIC

25 posts | 3 followers

Related Products

  • IoT Platform

    Provides secure and reliable communication between devices and the IoT Platform which allows you to manage a large number of devices on a single IoT Platform.

    Learn More
  • IoT Solution

    A cloud solution for smart technology providers to quickly build stable, cost-efficient, and reliable ubiquitous platforms

    Learn More
  • Link IoT Edge

    Link IoT Edge allows for the management of millions of edge nodes by extending the capabilities of the cloud, thus providing users with services at the nearest location.

    Learn More