So I took directly from Azure (https://docs.microsoft.com/pt-br/azure/iot-hub/iot-hub-devguide-security) a Python code to generate the SaS Token. I made the necessary adaptations for my application, but when I use the generated token to send data via POST it returns the following message:
"Message":"ErrorCode:IotHubUnauthorizedAccess;Unauthorized","ExceptionMessage":"Tracking ID:c8b0d18b771e465081aa9324293adf73-G:1-TimeStamp:09/08/2020 19:53:52"
I know how to generate the token using Azure tools in VS Code, but I would like this generation to be incorporated in the code. Below is the code I am using. (Of course, replacing Device ID, Iot Hub Name and the key with those available on the microsoft portal.)
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
rawtoken['se'] = str(int(ttl))
return 'SharedAccessSignature ' + parse.urlencode(rawtoken)
resource_uri = IoTHubName + ".azure-devices.net" + "/" + "devices" + "/" + deviceID
policy_name = "iothubowner"
uri = resource_uri
key = "primary key="
expiry = 3600
policy= "iothubowner"
print (generate_sas_token(uri, key, policy, expiry))