使用Azure SDK获取Microsoft Graph令牌时,如何动态配置权威主机?
动态根据API主机设置Azure权威主机解决跨云请求错误
当使用azure.identity.aio的ClientSecretCredential调用国家云环境的Graph API(如graph.microsoft.us、graph.microsoft.de、graph.microsoft.cn)时,若未指定对应权威主机,会触发Confidential Client is not supported in Cross Cloud request错误。可以通过建立主机名与权威主机的映射关系,实现动态匹配对应的authority参数。
实现方案
- 导入
AzureAuthorityHosts枚举,它包含官方维护的所有Azure云环境权威主机地址 - 创建Graph主机到权威主机的映射字典,覆盖需要支持的云环境
- 根据传入的目标主机名,动态选择对应的权威主机初始化
ClientSecretCredential
示例代码
from azure.identity.aio import ClientSecretCredential from azure.identity import AzureAuthorityHosts # 映射Graph主机到对应云环境的权威主机 GRAPH_HOST_AUTHORITY_MAP = { "graph.microsoft.com": AzureAuthorityHosts.AZURE_PUBLIC_CLOUD, "graph.microsoft.us": AzureAuthorityHosts.AZURE_GOVERNMENT, "graph.microsoft.de": AzureAuthorityHosts.AZURE_GERMANY, "graph.microsoft.cn": AzureAuthorityHosts.AZURE_CHINA } def create_credential(tenant_id: str, client_secret: str, target_host: str) -> ClientSecretCredential: # 根据目标主机获取对应的权威主机,无匹配则抛出异常 authority = GRAPH_HOST_AUTHORITY_MAP.get(target_host) if not authority: raise ValueError(f"不支持的主机地址: {target_host}") return ClientSecretCredential( tenant_id=tenant_id, client_secret=client_secret, authority=authority ) # 异步调用示例 async def get_access_token(tenant_id: str, client_secret: str, target_host: str): credential = create_credential(tenant_id, client_secret, target_host) # 构造对应主机的scope scope = f"{target_host}/.default" access_token = await credential.get_token(scope) return access_token.token
注意事项
- 若需要支持其他国家云主机,只需在
GRAPH_HOST_AUTHORITY_MAP中添加对应的键值对即可 - 确保
get_token的scope参数与目标主机一致,格式为{host}/.default - 由于使用的是异步版本SDK,所有涉及
ClientSecretCredential的调用需遵循异步规范(使用await)
内容的提问来源于stack exchange,提问作者saz
相关产品推荐
相关产品推荐

