Python项目:Azure PIM中授予RBAC权限的Graph API端点查询
通过Graph API在Azure PIM中授予RBAC权限的可行性及实现方式
完全可行,针对Azure PIM的RBAC权限授予,Graph API提供了专门的端点,分两种核心场景:
Azure AD角色的PIM权限管理
- 授予角色资格(用户可自行激活):使用
POST /roleManagement/directory/roleEligibilityScheduleRequests - 直接分配激活的角色(即时生效):使用
POST /roleManagement/directory/roleAssignmentScheduleRequests
- 授予角色资格(用户可自行激活):使用
Azure资源角色的PIM权限管理
- 授予角色资格:使用
POST /roleManagement/resources/roleEligibilityScheduleRequests - 直接分配激活的角色:使用
POST /roleManagement/resources/roleAssignmentScheduleRequests
- 授予角色资格:使用
权限要求
调用这些端点需要对应的权限:
- 针对Azure AD角色:
RoleManagement.ReadWrite.Directory - 针对Azure资源角色:
RoleManagement.ReadWrite.ResourceManager
同时,发起请求的身份(应用或用户)需要在Azure AD中被分配Privileged Role Administrator等PIM管理员角色。
Python实现核心步骤
- 使用
msal库获取Graph API的访问令牌,完成身份验证 - 构造请求体,明确目标角色ID、用户ID、分配类型、有效期等关键参数
- 发送POST请求到对应端点
以下是一个简单的示例代码(针对Azure资源角色直接分配):
import requests import msal # 配置身份验证参数 client_id = "你的客户端ID" client_secret = "你的客户端密钥" tenant_id = "你的租户ID" authority = f"https://login.microsoftonline.com/{tenant_id}" scope = ["https://graph.microsoft.com/.default"] # 获取访问令牌 app = msal.ConfidentialClientApplication( client_id, authority=authority, client_credential=client_secret ) token_result = app.acquire_token_for_client(scopes=scope) access_token = token_result.get("access_token") # 构造PIM角色分配请求 api_url = "https://graph.microsoft.com/v1.0/roleManagement/resources/roleAssignmentScheduleRequests" headers = { "Authorization": f"Bearer {access_token}", "Content-Type": "application/json" } request_body = { "action": "AdminAssign", "justification": "项目需求临时授予PIM权限", "roleDefinitionId": "/subscriptions/{订阅ID}/providers/Microsoft.Authorization/roleDefinitions/{角色定义ID}", "directoryScopeId": "/subscriptions/{订阅ID}", "principalId": "{用户对象ID}", "scheduleInfo": { "startDateTime": "2024-05-20T00:00:00Z", "expiration": { "type": "AfterDuration", "duration": "PT8H" } } } # 发送请求 response = requests.post(api_url, headers=headers, json=request_body) print(response.json())
内容的提问来源于stack exchange,提问作者mbt
相关产品推荐
相关产品推荐

