You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

通过AppRoleId获取服务主体的声明值/应用角色名称(PowerShell)

问题:获取服务主体应用角色分配对应的权限名称

我使用以下PowerShell命令查询单个服务主体的应用角色分配:

Get-MgServicePrincipalAppRoleAssignment -ServicePrincipalId <id>

返回结果如下:

AppRoleId            : df021288-bdef-4463-88db-98f22de89214
CreatedDateTime      : 2022-11-24 08:32:38
DeletedDateTime      :
Id                   : <Id>
PrincipalDisplayName : <PrincipalDisplayName>
PrincipalId          : <PrincipalId>
PrincipalType        : ServicePrincipal
ResourceDisplayName  : Microsoft Graph
ResourceId           : <ResourceId>
AdditionalProperties : {}

结果中缺少我需要的应用角色名称(例如本例中的User.Read.All),请问如何通过PowerShell查询Azure门户中可分配权限的Microsoft API(如Graph API、Office 365管理API等)对应的这些名称?


解决方案

1. 获取目标API的服务主体详情

根据返回结果中的ResourceId(即目标API的服务主体ID),获取该API的所有可用应用角色:

# 替换<ResourceId>为查询结果中的资源ID
$apiServicePrincipal = Get-MgServicePrincipal -ServicePrincipalId <ResourceId>

2. 匹配AppRoleId提取权限名称

从服务主体对象的AppRoles集合中,筛选出与目标AppRoleId匹配的条目,即可得到对应的权限名称(Value字段)和显示名:

# 替换<AppRoleId>为查询结果中的AppRoleId
$targetRole = $apiServicePrincipal.AppRoles | Where-Object { $_.Id -eq "<AppRoleId>" }
# 输出权限信息
Write-Host "权限名称: $($targetRole.Value)"
Write-Host "权限显示名: $($targetRole.DisplayName)"

3. 批量导出所有应用角色分配及权限名称

如果需要一次性获取某个服务主体的所有应用角色分配及其对应权限名称,可以使用以下脚本:

# 替换<ServicePrincipalId>为目标服务主体的ID
$allAssignments = Get-MgServicePrincipalAppRoleAssignment -ServicePrincipalId <ServicePrincipalId>

foreach ($assignment in $allAssignments) {
    $resourceSp = Get-MgServicePrincipal -ServicePrincipalId $assignment.ResourceId
    $matchedRole = $resourceSp.AppRoles | Where-Object { $_.Id -eq $assignment.AppRoleId }
    
    # 输出结构化结果
    [PSCustomObject]@{
        主体显示名       = $assignment.PrincipalDisplayName
        资源API名称      = $assignment.ResourceDisplayName
        权限名称         = $matchedRole.Value
        权限显示名       = $matchedRole.DisplayName
        角色ID           = $assignment.AppRoleId
        分配创建时间     = $assignment.CreatedDateTime
    }
}

内容的提问来源于stack exchange,提问作者ChristofferL

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 20:21:12