在Azure自动化账户中用PowerShell无法列出Azure AD应用的权限问题
我创建了一个基于PowerShell 5.1的Azure自动化账户Runbook,通过名为“local”的连接关联了一个服务主体,并配置了对应权限。
运行代码
$connection = Get-AutomationConnection -Name "local" try { Write-Output 'Connecting to services' Connect-AzureAD -TenantId $connection.TenantID -ApplicationId $connection.ApplicationID -CertificateThumbprint $connection.CertificateThumbprint | Out-null } catch { Write-Error -Message $_.Exception.Message Disconnect-AzureAD | Out-null Break } Write-Output "Connect process done" # Function try { Write-Output 'List all apps' $list = Get-AzureADApplication -All $true Write-Output $list } Catch { Write-Error -Message $_.Exception.Message Disconnect-AzureAD }
(注:原代码中冗余的$true行已移除,避免语法错误)
首次运行错误
Error occurred while executing GetApplications Code: Authorization_RequestDenied Message: Insufficient privileges to complete the operation. GMT HttpStatusCode: Forbidden HttpStatusDescription: Forbidden HttpResponseStatus: Completed + CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException
我不清楚为何权限未生效,该如何解决?
补充操作后仍报错
编辑:我已为服务主体授予Directory Read权限,但仍出现如下相同类型错误:
Error occurred while executing GetApplications Code: Authorization_RequestDenied Message: Insufficient privileges to complete the operation. HttpStatusCode: Forbidden HttpStatusDescription: Forbidden HttpResponseStatus: Completed + CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException
解决方法
确认权限类型正确:
Get-AzureADApplication依赖的是Azure AD Graph API权限,而非Azure RBAC权限。需给服务主体添加以下应用权限(服务主体场景必须用应用权限):Application.Read.All:允许读取租户内所有应用- 若仅需读取服务主体拥有的应用,可使用
Application.Read.OwnedBy
单纯授予"Directory Read"(目录读取RBAC权限)无法满足API调用需求。
完成管理员同意:添加API权限后,必须在Azure AD的「应用注册」→ 对应服务主体 →「API权限」页面点击授予管理员同意,否则权限不会生效。
检查权限范围:确保权限是授予在整个租户范围内,而非特定资源或应用。部分高权限API需要全局管理员角色完成同意操作。
验证连接上下文:在Runbook中添加调试代码,确认连接后的会话信息是否正确:
# 连接成功后插入以下代码 $currentContext = Get-AzureADCurrentSessionInfo Write-Output "当前租户ID: $($currentContext.TenantId)" Write-Output "当前应用ID: $($currentContext.ClientId)"确认会话使用的是目标服务主体和租户。
更新AzureAD模块:检查自动化账户中的AzureAD模块版本,若版本过旧可能存在权限兼容问题。在Azure自动化账户的「模块」页面找到AzureAD模块并更新至PowerShell 5.1支持的最新版本。
排查访问限制:检查服务主体是否被条件访问策略限制访问Azure AD Graph API,可在Azure AD的「条件访问」页面排查相关规则。
内容的提问来源于stack exchange,提问作者lviswa

