Skip to content
Advertisement

Generate SAS token with expiry for Azure IoT Hub in Python

I have an IoT Hub with various devices set up with SAS authentication. From the docs, I understand how to connect to a device with the IoT Hub connection string however I wish to know how to utilise an SAS token.

from base64 import b64encode, b64decode
from hashlib import sha256
from time import time
from urllib import parse
from hmac import HMAC

def generate_sas_token(uri, key, policy_name, expiry=3600):
    ttl = time() + expiry
    sign_key = "%sn%d" % ((parse.quote_plus(uri)), int(ttl))
    print(sign_key)
    signature = b64encode(HMAC(b64decode(key), sign_key.encode('utf-8'), sha256).digest())

    rawtoken = {
        'sr' :  uri,
        'sig': signature,
        'se' : str(int(ttl))
    }

    if policy_name is not None:
        rawtoken['skn'] = policy_name

    return 'SharedAccessSignature ' + parse.urlencode(rawtoken)

I have found this function in the docs but I am struggling to understand how to use this token.

Questions

  1. Could someone give me an example of how to use this token to connect to IoT Hub API?
  2. If I need an expiry on the token, does this mean the Shared Access Key will have to be regenerated and if so, can I do this programatically?

Thanks in advance :)

Advertisement

Answer

If you’re using MQTT: As the answer of @PlaidMode states, the SAS token can be used as the password value in an MQTT client. The linked document also describes what other values are needed. If you’re using HTTP instead, the same token is the value of the Authorization header.

As for your second question, the expiry is required, there is no way around it. However, there is no limit to what this expiry can be, you can make it as long as you want (whether you should is a different question). After the key has expired, you need to create a new one. You can use the same code as you have included in your question to do so.

Advertisement