如何从Azure SDK DefaultCredential获取Bearer Token用于Azure AD应用证书管理
解决方案
1. 从DefaultAzureCredential获取可直接使用的Bearer Token
DefaultAzureCredential实例提供了get_token()方法,传入对应接口的scope参数即可生成有效token,且该方法会自动处理token过期刷新逻辑,无需手动维护过期时间。
示例代码如下:
from azure.identity import DefaultAzureCredential import requests # 初始化凭证,默认会自动读取当前环境的Azure身份配置(如环境变量、Azure CLI登录身份、托管身份等) default_credential = DefaultAzureCredential() # 调用Microsoft Graph API的固定scope值 GRAPH_SCOPE = "https://graph.microsoft.com/.default" def get_valid_bearer_token(): # 自动检测token过期情况,过期会自动刷新返回有效凭证 token_obj = default_credential.get_token(GRAPH_SCOPE) return token_obj.token # 调用Graph API获取应用注册列表示例 def get_all_app_registrations(): access_token = get_valid_bearer_token() headers = { "Authorization": f"Bearer {access_token}", "Content-Type": "application/json" } resp = requests.get("https://graph.microsoft.com/v1.0/applications", headers=headers) resp.raise_for_status() return resp.json()
2. 提取即将过期的证书/密钥信息
从applications接口返回的结果中,keyCredentials字段存储证书信息,passwordCredentials字段存储客户端密钥信息,其中endDateTime为过期时间,可通过该字段筛选即将过期的凭证:
from datetime import datetime, timezone def get_expiring_credentials(app_list, threshold_days=30): expiring_list = [] current_time = datetime.now(timezone.utc) for app in app_list.get("value", []): app_name = app.get("displayName") app_id = app.get("appId") # 筛选即将过期的证书 for cert in app.get("keyCredentials", []): expire_time = cert.get("endDateTime") if not expire_time: continue remaining_days = (expire_time - current_time).days if remaining_days < threshold_days: expiring_list.append({ "凭证类型": "证书", "应用名称": app_name, "应用ID": app_id, "凭证名称": cert.get("displayName"), "剩余有效天数": remaining_days, "过期时间": expire_time.strftime("%Y-%m-%d %H:%M:%S UTC") }) # 筛选即将过期的客户端密钥 for secret in app.get("passwordCredentials", []): expire_time = secret.get("endDateTime") if not expire_time: continue remaining_days = (expire_time - current_time).days if remaining_days < threshold_days: expiring_list.append({ "凭证类型": "客户端密钥", "应用名称": app_name, "应用ID": app_id, "凭证名称": secret.get("displayName"), "剩余有效天数": remaining_days, "过期时间": expire_time.strftime("%Y-%m-%d %H:%M:%S UTC") }) return expiring_list
注意事项
- 运行代码的身份需要提前配置对应权限:仅读取应用信息需要授予Microsoft Graph的
Application.Read.All权限,如需自动续期还要额外授予Application.ReadWrite.All权限,且权限需要完成管理员同意。 DefaultAzureCredential会按优先级自动适配身份:依次尝试环境变量配置的服务主体、当前Azure CLI登录身份、Azure托管身份、VSCode Azure插件登录身份,本地调试和线上部署无需修改代码,只需配置对应环境的身份即可。- 自动续期操作可以调用Microsoft Graph的
applications/{应用对象ID}/addKey(证书续期)、addPassword(客户端密钥续期)接口完成,生成新凭证后请妥善存储凭证内容。
内容的提问来源于stack exchange,提问作者Ayush Ujjwal
相关产品推荐
相关产品推荐

