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

【Azure Developer】Python代码获取的Token出现'Authentication_MissingOrMalformed'问题

 

 

所以:如果发现通过 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 
        }

 


 

相关文章:

  • 2022-12-23
  • 2021-09-16
  • 2022-12-23
  • 2021-06-25
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-15
猜你喜欢
  • 2021-11-17
  • 2022-12-23
  • 2021-07-24
  • 2021-06-07
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案