简体   繁体   中英

How to generate headers for azure cosmos db to make rest api requests

I want to get Docs from my azure cosmos db but I am getting unauthorized error and I know its related to resource id and resource type string format. Please help in constructing right string.

import requests
import hmac
import hashlib
import base64
from datetime import datetime
import urllib.parse
key = '<key>=='
now = datetime.utcnow().strftime('%a, %d %b %Y %H:%M:00 GMT')
print(now)
payload = ('get\ndocs\ndbs/iot/colls/messages\n' + now + '\n\n').lower()


payload = bytes(((payload)),encoding='utf8')
key = base64.b64decode(key.encode('utf-8'))

signature = base64.b64encode(hmac.new(key, msg = payload, digestmod = 
hashlib.sha256).digest()).decode()
print(signature)

authStr = urllib.parse.quote('type=master&ver=1.0&sig={}'.format(signature))
print("key = " ,authStr)

headers = {
'Authorization': authStr,
"x-ms-date": now,
"x-ms-version": "2017-02-22"
}
url = 'https://rpi.documents.azure.com/dbs/iot/colls/messages'
res = requests.get(url, headers = headers)
print(res.content)

I noticed there's an extra new line character in your payload (after messages )

payload = ('get\ndocs\ndbs\iot\colls\messages\n\n' + now + '\n\n').lower()

Moreover resourceLink also seems incorrect. You're using \\ instead of / in the resource link.

Can you try by changing it to:

payload = ('get\ndocs\ndbs/iot/colls/messages\n' + now + '\n\n').lower()

Also, please change your url from url = 'https://rpi.documents.azure.com/dbs' to url = 'https://rpi.documents.azure.com/dbs/iot/colls/messages' .

and see if that makes the difference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM