如何在python中为cosmos db生成其余的授权令牌?

时间:2018-04-08 03:03:34

标签: python rest azure-cosmosdb

我无法为简单的get数据库请求生成cosmos db的授权令牌。这是我的python代码:

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

产生此错误:

{"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"}

1 个答案:

答案 0 :(得分:4)

格雷格。根据我的观察,你的代码遗漏是url encode。您可以找到示例代码here

请参阅我的代码,该代码稍微调整了您的代码。

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

执行结果:

enter image description here

希望它对你有所帮助。

相关问题