使用Azure Python SDK v2.0创建应用注册时遇令牌错误
排查Azure Python SDK创建应用注册时的「Access Token missing or malformed」错误
我来帮你搞定这个令牌错误,这个问题大多和令牌的目标资源、凭据获取方式或者权限配置有关,咱们一步步来解决:
1. 先修正凭据的资源目标(最常见原因)
你用的get_azure_cli_credentials()默认是获取Azure资源管理器(ARM)的访问令牌,但Graph RBAC API需要的是Azure AD Graph的令牌(资源URI为https://graph.windows.net/)。不指定资源的话,拿到的令牌和API不匹配,就会报令牌无效的错误。
修改代码,在获取凭据时指定资源:
from azure.common.credentials import get_azure_cli_credentials from azure.graphrbac import GraphRbacManagementClient # 关键:指定Graph资源URI credentials, subscription_id = get_azure_cli_credentials(resource="https://graph.windows.net/") client = GraphRbacManagementClient(credentials, 'my-tenant-id') app_parameters = { 'available_to_other_tenants': False, 'display_name': 'my-app-name', 'identifier_uris': ['http://my-app-name.com'] } # 现在再调用create试试 app = client.applications.create(app_parameters)
2. 验证当前CLI用户的权限
就算令牌对了,没有足够的权限也会出问题。确保你登录CLI的用户拥有以下角色之一:
- 全局管理员
- 应用程序管理员
- 或者拥有
Application.ReadWrite.All这样的Azure AD权限
你可以用CLI快速检查当前用户的角色:
az ad signed-in-user show --query "assignedRoles[*].displayName"
如果权限不足,需要让Azure AD管理员给你分配对应的角色。
3. 确认租户ID是否正确
代码里的my-tenant-id必须是你要创建应用注册的租户的正确ID,错了的话令牌的受众会不匹配。用下面的CLI命令获取当前登录的租户ID:
az account show --query "tenantId" -o tsv
把输出的ID替换到代码里。
4. 考虑迁移到更现代的SDK(可选但推荐)
注意azure-graphrbac这个包已经被微软标记为废弃了,现在更推荐用azure-mgmt-graphrbac配合azure-identity凭据包,或者直接用Microsoft Graph SDK。这里给你一个用新SDK的示例,稳定性更好:
首先安装依赖:
pip install azure-identity azure-mgmt-graphrbac
然后修改代码:
from azure.identity import AzureCliCredential from azure.mgmt.graphrbac import GraphRbacManagementClient credential = AzureCliCredential() client = GraphRbacManagementClient(credential, 'my-tenant-id') app_parameters = { 'available_to_other_tenants': False, 'display_name': 'my-app-name', 'identifier_uris': ['http://my-app-name.com'] } app = client.applications.create(app_parameters)
AzureCliCredential会自动处理资源URI的问题,不需要手动指定。
5. 调试令牌内容(排障终极手段)
如果上面的方法都不行,可以把令牌打出来看看哪里有问题:
# 在创建client之后添加这行 token = credentials.token["access_token"] print(token)
然后用JWT解析工具查看令牌的关键字段:
aud:受众必须是https://graph.windows.net/exp:过期时间必须在当前时间之后roles:必须包含创建应用注册的权限(比如Application.ReadWrite.All)
内容的提问来源于stack exchange,提问作者Matt Skone
相关产品推荐
相关产品推荐

