問題描述
使用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