Generating a Shared Access Signature Token (SAS) for IoT Hub

Blogs are 1% about sharing information with others and 99% about sharing information with your self and this post is no different. From time to time I have to generate a SAS token for either connecting to IoT Hub from a device or service. The Azure IoT Hub CLI allows you to generate SAS tokens for most scenarios expect for one: When you only have the device name, host and key. I am not sure why this option is not available via the CLI but lucky for us, there is an easy way around it.

Azure Function

When you use any of the SDKs to connect to IoT Hub, the SDKs automatically generate the SAS token for you. Using the Node SDK, I created a simple Azure Function to help me generate a token.

All you need is the code bellow and the Node SDK ( npm iĀ azure-iot-device ). You can pass the variables via the request body to make it easier to reuse.

module.exports = function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    var host = '';
    var deviceId = '';
    var devkey = '';

    // an hour from now in seconds. Customers should pick their own expiry
    var expiry = (new Date() / 1000) + 3600; 
    var deviceUri = encodeURIComponent(host + '/devices/' + deviceId);
    var sas = require('azure-iot-common').SharedAccessSignature.create(deviceUri,null, devkey, expiry);

    context.log(sas.toString());
       
    context.res = {
        status: 400,
        body: sas.toString()
    };
    context.done();
}

Leave a Reply

Your email address will not be published. Required fields are marked *