如何用Azure Python SDK实现`az ad app list`并解决403权限错误
使用Microsoft Graph Python SDK实现
az ad app list功能的权限问题解决 问题背景
原本使用已弃用的azure-graphrbac包实现az ad app list的功能,按照官方建议改用Microsoft Graph API后,编写了代码但触发403权限拒绝错误,已为应用分配Azure Reader角色但无效。
编写的代码
import asyncio from azure.identity import DefaultAzureCredential from msgraph import GraphServiceClient from dotenv import load_dotenv load_dotenv() credential = DefaultAzureCredential() client = GraphServiceClient(credential) async def main(): result = await client.applications.get() return result asyncio.run(main())
错误信息
msgraph.generated.models.o_data_errors.o_data_error.ODataError: APIError Code: 403 message: None error: MainError(additional_data={}, code='Authorization_RequestDenied', details=None, inner_error=InnerError(additional_data={'date': DateTime(2023, 12, 7, 5, 41, 17, tzinfo=Timezone('UTC'))}, client_request_id='ee33797c-1ae4-4a00-99bd-5cf8ed30301b', date=None, odata_type=None, request_id='b5d36ffa-5cdc-4c7c-aaa9-9aef55bcf5ab'), message='Insufficient privileges to complete the operation.', target=None)
解决方法
Azure Reader角色是针对Azure资源的RBAC权限,无法访问Microsoft Graph API。必须为应用注册分配Microsoft Graph的应用权限:
- 所需权限:
Application.Read.All(应用权限,允许读取所有应用注册信息) - 操作步骤:
- 登录Azure门户,找到对应的应用注册
- 进入「API权限」页面
- 点击「添加权限」→ 选择「Microsoft Graph」→ 选择「应用权限」
- 搜索并勾选
Application.Read.All权限,点击「添加权限」 - 点击「授予管理员同意」(需要全局管理员或应用程序管理员权限)
- 等待权限生效后重新运行代码
补充说明
默认client.applications.get()只返回前100条结果,如果需要获取所有应用,需处理分页:
async def main(): all_apps = [] page = await client.applications.get() all_apps.extend(page.value) while page.odata_next_link: page = await client.applications.get(url=page.odata_next_link) all_apps.extend(page.value) return all_apps
内容的提问来源于stack exchange,提问作者shn
相关产品推荐
相关产品推荐

