import urllib.parse
import hmac
import hashlib
import base64
import time
def get_auth_token(sb_name, queue_name, sas_name, sas_value):
"""
Returns an authorization token dictionary
for making calls to Service Bus REST API.
"""
uri = urllib.parse.quote_plus("https://{}.servicebus.windows.net/{}" \
.format(sb_name, queue_name))
sas = sas_value.encode('utf-8')
expiry = str(int(time.time() + 10000))
string_to_sign = (uri + '\n' + expiry).encode('utf-8')
signed_hmac_sha256 = hmac.HMAC(sas, string_to_sign, hashlib.sha256)
signature = urllib.parse.quote(base64.b64encode(signed_hmac_sha256.digest()))
return {"sb_name": sb_name,
"queue_name": queue_name,
"token":'SharedAccessSignature sr={}&sig={}&se={}&skn={}' \
.format(uri, signature, expiry, sas_name)
}
sb_name = "my_service_bus"
queue_name = "my_queue"
sas_name = "shared_access_policy_name"
sas_value = "my_primary_key"
auth_token = get_auth_token(sb_name, queue_name, sas_name, sas_value)
print(auth_token["token"])
Code works and returns token. But when the token is used as a Bearer token in Rest api POST request it returns:
<Error>
<Code>401</Code>
<Detail>MalformedToken: Failed to parse simple web token. TrackingId:ac03ae94-ba77-46e4-a237-99cd8dc9ba83_G78, SystemTracker:whepservice.servicebus.windows.net:whepq, Timestamp:2023-04-06T15:26:53</Detail>
</Error>
Can You help to successfully authenticate to the service bus queue? Thank you in advance.
Instead of using token as bearer token, use the obtained token as Authorization.
I have run the code provided by you and I got token as shared access signature.
I would suggest you try connecting service bus queue through postman and see if you are able to authenticate properly.
Below are steps you can follow to test authentication using postman.
Ran the code provided by you and got token in below format,
Request Type: POST
Url: Format:https://.servicebus.windows.net//messages
Content-Type: application/json
Authorization: SharedAccessSignature sr=https%3A%2F%2F.servicebus.windows.net%2F&sig=&se=1438205742&skn=KeyName
ContentType: application/atom+xml;type=entry;charset=utf-8
Use the obtained token as Authorization as shown below,
Try to send sample message from body as shown below,
Check if you are able to send the message without getting authorization error. If you are able to authorize properly through postman, then there is some issue with passing token.
Also token you are getting is in proper format as mentioned in above.
Reference link