如何在python中为cosmos db生成其余授权令牌? [英] How do I generate the rest authorization token for cosmos db in python?

查看:76
本文介绍了如何在python中为cosmos db生成其余授权令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法为一个简单的get database请求为cosmos db生成授权令牌.这是我的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

哪个会产生此错误:

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

推荐答案

Greg.根据我的观察,您的代码缺失为url encode.您可以找到示例代码此处.

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

执行结果:

希望它对您有帮助.

这篇关于如何在python中为cosmos db生成其余授权令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆