Greg Clinton
Greg Clinton

Reputation: 375

How do I generate the rest authorization token for cosmos db in python?

I'm having trouble generating the authorization token for cosmos db for a simple get databases request. Here is my python code:

import requests
import hmac
import hashlib
import base64
from datetime import datetime

key = 'AG . . .EZPcZBKz7gvrKiXKsuaPA=='
now = datetime.utcnow().strftime('%a, %d %b %Y %H:%M:00 GMT')
payload = ('get\ndbs\n\n' + now + '\n\n').lower()
signature = base64.b64encode(hmac.new(key, msg = payload, digestmod = hashlib.sha256).digest()).decode()

url = 'https://myacct.documents.azure.com/dbs'
headers = {
    'Authorization': "type=master&ver=1.0&sig=" + signature,
    "x-ms-date": now,
    "x-ms-version": "2017-02-22"
}

res = requests.get(url, headers = headers)
print res.content

Which produces this error:

{"code":"Unauthorized","message":"The input authorization token can't serve the request. Please check that the expected payload is built as per the protocol, and check the key being used. Server used the following payload to sign: 'get\ndbs\n\nsun, 08 apr 2018 02:39:00 gmt\n\n'\r\nActivityId: 5abe59d8-f44e-42c1-9380-5cf4e63425ec, Microsoft.Azure.Documents.Common/1.21.0.0"}

Upvotes: 1

Views: 3321

Answers (1)

Jay Gong
Jay Gong

Reputation: 23782

Greg. Per my observe, the miss of your code is url encode. You could find the sample code here.

Please refer to my code which was made a slight adjustment to your code.

import requests
import hmac
import hashlib
import base64
from datetime import datetime
import urllib

key = '***'
now = datetime.utcnow().strftime('%a, %d %b %Y %H:%M:00 GMT')
print now
payload = ('get\ndbs\n\n' + now + '\n\n').lower()

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

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

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

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

Execute result:

enter image description here

Hope it helps you.

Upvotes: 4

Related Questions