【Azure Developer】Python代码获取的Token出现'Authentication_MissingOrMalformed'问题 - LuBu0505/My-Code GitHub Wiki
问题描述
Python 调用Azure AD中所注册的应用生成Token代码:
import requests, json
client_id = 'yourclientid'
client_secret = 'yourclientsecret'
tokenUrl = 'https://login.chinacloudapi.cn/yourtenantid/oauth2/token?api-version=1.0'
data = {
'grant_type': 'client_credentials',
'client_id': client_id,
'resource': 'https://management.chinacloudapi.cn/',
'client_secret': client_secret
}
rToken = requests.post(tokenUrl, data=data)
#print(rToken) # 404 not found
token = rToken.json().get('access_token')
headers = {
'Content-Type' : 'application\json',
'Authorization': 'Bearer {}'.format(token)
}
url = "https://management.chinacloudapi.cn/subscriptions/yoursubid/resourceGroups/yourgroupname/providers/Microsoft.Compute/virtualMachines/yourvmname?api-version=2020-06-01"
r = requests.get(url, headers=headers)
result = r.json()
print(result)
在使用时候出现:
{'odata.error': {'code': 'Authentication_MissingOrMalformed', 'message': {'lang': 'en', 'value': 'Access Token missing or malformed.'}, 'requestId': '4a241f2e-997e-4eaa-23dd-807df708b81b', 'date': '2021-12-03T12:13:39'}}
问题分析
从错误消息来看,提示为Token错误。而AAD的Token都是JWT格式,所以可以使用任何在线解析工具直接查看JWT中的内容,第一是验证格式是否正确,第二是判断内容aud等内容是否匹配。
如 https://www.box3.cn/tools/jwt.html
所以:如果发现通过 JWT 解析 Token,发现受众aud是 https://management.chinacloudapi.cn,所以使用此Token是无法调用 https://graph.chinacloudapi.cn 的接口的,需要在获取Token的请求Data中把resource由
https://management.chinacloudapi.cn/ 修改为 https://graph.chinacloudapi.cn
data = {
'grant_type': 'client_credentials',
'client_id': client_id,
'resource': 'https://graph.chinacloudapi.cn',
'client_secret': client_secret
}
当在复杂的环境中面临问题,格物之道需:浊而静之徐清,安以动之徐生。 云中,恰是如此!
分类: 【Azure Developer】
标签: Azure Developer, Python AAD Token