【Azure Developer】【Python 】使用 azure.identity 和 azure.common.credentials 获取Azure AD的Access Token的两种方式
问题描述
使用Python代码,展示如何从Azure AD 中获取目标资源的 Access Token。
如要了解如何从AAD中获取 client id,client secret,tenant id,请参考博文:【Azure Developer】Python代码通过AAD认证访问微软Azure密钥保管库(Azure Key Vault)中机密信息(Secret) 中的操作步骤一栏。
代码展示
获取方式一:使用 azure.identity
1)调用 ClientSecretCredential 方法,通过client_id, client_secret ,tenant_id 以及 authority=AzureAuthorityHosts.AZURE_CHINA,初始化 credentials 对象
2)调用对象中的 get_token方法,特别注意参数 scopes 的传递,如 "https://microsoftgraph.chinacloudapi.cn/.default", 如果缺少.default,则会提示参数错误(详见[遇见问题]部分)
from azure.identity import ClientSecretCredential credentials = ClientSecretCredential(client_id='xxxxxxxx-xxxx-xxxx-xxxx-76f50363af33', client_secret='.~V9ij1.5Y_F8rL_k8DNpj~RSLFf~H56nH', tenant_id='xxxxxxxx-xxxx-xxxx-xxxx-1316152d9587',authority=AzureAuthorityHosts.AZURE_CHINA) token =credentials.get_token("https://microsoftgraph.chinacloudapi.cn/.default") print(token)
调用方式二:使用 azure.common.credentials
1) 调用 ServicePrincipalCredentials 方法,同样通过参数 client_id, secret, tenant, resource 和 china='true' , 初始化 credentials 对象
2) 解析credentials对象,获取Token中的 access_token属性值。credentials.token['access_token']
print("方式二: ServicePrincipalCredentials") from azure.common.credentials import ServicePrincipalCredentials credentials = ServicePrincipalCredentials(client_id='xxxxxxxx-xxxx-xxxx-xxxx-76f50363af33', secret='.~xxxx.xxxx~xxxx~xxxx', tenant='xxxxxxxx-xxxx-xxxx-xxxx-1316152d9587', resource='https://microsoftgraph.chinacloudapi.cn/', china='true') access_token = credentials.token['access_token'] print(access_token)
方式一和方式二执行的结果相同
PS: 使用 https://jwt.io/ 可以Decoded token 内容。已可读方式查看。
遇见问题
错误一:get_token 提示 requires at least one scope。
Traceback (most recent call last): File "client.py", line 7, in <module> print(credentials.get_token(scopes="")) File "C:\Users\bulu\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\azure\identity\_internal\get_token_mixin.py", line 64, in get_tokent_token_mixin.py", line 64,
in get_token raise ValueError('"get_token" requires at least one scope') ValueError: "get_token" requires at least one scope
错误的原因就是输入的scope参数不正确。需要输入“https://microsoftgraph.chinacloudapi.cn/.default" 携带.default。
The
/.default
scope is built in for every application that refers to the static list of permissions configured on the application registration. Source: https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#the-default-scope
参考资料
The /.default scope: https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#the-default-scope
identity Package: https://docs.microsoft.com/zh-cn/python/api/azure-identity/azure.identity?view=azure-python
AzureAuthorityHosts Class:https://docs.microsoft.com/zh-cn/python/api/azure-identity/azure.identity.azureauthorityhosts?view=azure-python
当在复杂的环境中面临问题,格物之道需:浊而静之徐清,安以动之徐生。 云中,恰是如此!