Reputation: 408
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
Thanks in advance :)
Upvotes: 0
Views: 885
Reputation: 4095
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.
Upvotes: 1
Reputation: 37
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.
Upvotes: 0