使用Azure B2C Python SDK访问资源失败:令牌缺失或格式错误
问题:Azure GraphRBAC Python SDK调用失败(Access Token缺失或格式错误)
已验证的REST调用方式(可正常执行)
通过直接调用Microsoft Graph REST API,能成功获取令牌并查询用户:
token_url: str = f"https://login.microsoftonline.com/{tenant_domain_name}/oauth2/v2.0/token" my_credentials = { 'client_id': my_client_id, 'scope': 'https://graph.microsoft.com/.default', 'client_secret': my_secret, 'grant_type': 'client_credentials' } response = requests.post(token_url, data = my_credentials) users_url: str = 'https://graph.microsoft.com/v1.0/users/' response_data = response.json() auth_headers = {"Authorization": f"Bearer {response_data['access_token']}"} response = requests.get(users_url, headers=auth_headers)
尝试的SDK代码(执行报错)
使用Azure GraphRBAC SDK尝试实现相同功能时,在遍历用户列表时抛出令牌错误:
credentials = ServicePrincipalCredentials( client_id=my_client_id, secret=my_secret, resource="https://graph.microsoft.com/", tenant=my_tenant_name ) graphrbac_client = GraphRbacManagementClient( credentials, my_tenant_id ) users: UserPaged = graphrbac_client.users.list() u: User = None for u in users: print(u.display_name)
抛出异常
Exception has occurred: GraphErrorException
Access Token missing or malformed.
File "/Users/{snip}/.venv/lib/python3.8/site-packages/azure/graphrbac/operations/users_operations.py", line 158, in internal_paging
问题原因与解决方案
核心原因
GraphRbacManagementClient是针对Azure AD Graph API(旧版API,已弃用)的客户端,而非你REST调用中使用的Microsoft Graph API。两者的令牌资源、权限体系完全不同,导致你用Microsoft Graph的令牌去调用Azure AD Graph的SDK,出现令牌格式错误。
解决方案1:改用Microsoft Graph Python SDK(推荐)
Microsoft Graph是Azure AD Graph的继任者,官方推荐使用。需要安装azure-identity和msgraph-sdk包:
pip install azure-identity msgraph-sdk
对应代码:
from azure.identity import ClientSecretCredential from msgraph import GraphServiceClient # 初始化凭据 credential = ClientSecretCredential( tenant_id=my_tenant_id, client_id=my_client_id, client_secret=my_secret ) # 初始化Graph客户端 graph_client = GraphServiceClient(credential) # 查询用户列表 users = graph_client.users.list() for user in users: print(user.display_name)
解决方案2:继续使用GraphRbacManagementClient(仅兼容旧版Azure AD Graph)
如果必须使用旧SDK,需要调整资源参数并确保服务主体拥有Azure AD Graph的权限:
- 修改凭据的
resource为Azure AD Graph的地址:https://graph.windows.net/ - 在Azure门户中,为服务主体添加Azure AD Graph的应用权限(而非Microsoft Graph的权限)
- 调整代码:
credentials = ServicePrincipalCredentials( client_id=my_client_id, secret=my_secret, resource="https://graph.windows.net/", tenant=my_tenant_name ) graphrbac_client = GraphRbacManagementClient( credentials, my_tenant_id ) users = graphrbac_client.users.list() for u in users: print(u.display_name)
内容的提问来源于stack exchange,提问作者gamey
相关产品推荐
相关产品推荐

