我有一些代码,我正在尝试根据Azure的Resource Manager REST API进行身份验证。
import json
import requests
tenant_id = "TENANT_ID"
app_id = "CLIENT_ID"
password = "APP_SECRET"
token_endpoint = 'http://login.microsoftonline.com/%s/oauth2/token' % tenant_id
management_uri = 'https://management.core.windows.net/'
payload = { 'grant_type': 'client_credentials',
'client_id': app_id,
'client_secret': password
}
auth_response = requests.post(url=token_endpoint, data=payload)
print auth_response.status_code
print auth_response.reason
返回:
200
OK
但是,当我打印auth_response.content或auth_responce.text时,我会返回一个400 HTML错误代码和一条错误消息。
HTTP Error Code: 400
Sorry, but we’re having trouble signing you in.
We received a bad request.
然而,我可以使用PostMan,使用相同的URI和有效载荷,返回正确的信息。我使用Postman中的"生成代码"选项将请求导出到Python请求脚本,并尝试运行该脚本。但是,我也有同样的错误。
有人知道为什么会发生这种事吗?
仅将token_endpoint
协议修改为https
协议。E.G:token_endpoint = 'https://login.microsoftonline.com/%s/oauth2/token' % tenant_id
。您可以参考https://msdn.microsoft.com/en-us/library/azure/dn645543.aspx了解更多详细信息。
同时,您可以利用Microsoft Azure Active Directory Authentication Library(ADAL)for Python轻松获取访问令牌。
对于token_endpoint,应该使用HTTPS而不是HTTP,并且还应该指定API版本。以下是您应该使用的内容。
token_endpoint = 'https://login.microsoftonline.com/%s/oauth2/token?api-version=1.0' % tenant_id