'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 = "%s\n%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
- Could someone give me an example of how to use this token to connect to IoT Hub API?
- 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 :)
Solution 1:[1]
I have some experience using paho-mqtt to connect to Azure IoT Hub. The SaS token is used as the password when connecting to the IoT Hub. Read the Microsoft Documentation on connecting to Azure IoT Hub using paho-mqtt.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | PlaidMode |
