如何通过PowerShell为Azure AD应用授予Microsoft Graph Directory.ReadAll权限
为Azure AD应用授予Microsoft Graph Directory.ReadAll权限(PowerShell实现)
你已完成Azure AD应用创建、客户端密钥生成及Reader角色分配,以下是为该应用授予Microsoft Graph Directory.ReadAll应用权限的具体实现步骤和整合代码:
实现逻辑
- 获取Microsoft Graph的服务主体对象,用于定位目标权限
- 筛选出Directory.ReadAll对应的应用权限ID
- 为你的Azure AD应用添加该权限
- 执行管理员同意(应用权限需管理员批准后方可生效)
完整整合代码
将新增的权限授予代码插入到现有脚本的Reader角色分配步骤之后即可:
#Connect to Azure AD Connect-AzAccount -TenantId <tenant-id> Connect-AzureAD #Set variables for the app $appName = "test" $secret = "MySecret" #Create the app $app = New-AzureADApplication -DisplayName $appName -PublicClient $false #Create the client secret $bytes = [System.Text.Encoding]::Unicode.GetBytes($secret) $base64 = [System.Convert]::ToBase64String($bytes) $startDate = Get-Date $endDate = $startDate.AddYears(1) $secret = New-AzureADApplicationPasswordCredential -ObjectId $app.ObjectId -CustomKeyIdentifier "MyCustomKeyIdentifier" -Value $base64 -StartDate $startDate -EndDate $endDate #Retrieve the tenant ID $tenantId = (Get-AzureADTenantDetail).ObjectId #giving Reader Role New-AzRoleAssignment -ObjectId $app.ObjectId -RoleDefinitionName "Reader" -PrincipalType "ServicePrincipal" # ------------------- 新增:授予Microsoft Graph Directory.ReadAll权限 ------------------- # 获取Microsoft Graph服务主体 $graphServicePrincipal = Get-AzureADServicePrincipal -Filter "DisplayName eq 'Microsoft Graph'" # 查找Directory.ReadAll应用权限的ID $directoryReadAllPermission = $graphServicePrincipal.AppRoles | Where-Object {$_.Value -eq "Directory.ReadAll" -and $_.AllowedMemberTypes -contains "Application"} # 为应用添加权限 New-AzureADApplicationAppRoleAssignment ` -ObjectId $app.ObjectId ` -PrincipalId $app.ObjectId ` -ResourceId $graphServicePrincipal.ObjectId ` -Id $directoryReadAllPermission.Id # 执行管理员同意(可选:若运行账号拥有全局管理员权限,可取消注释直接完成批准) # New-AzureADServicePrincipalAppRoleAssignment ` # -ObjectId (Get-AzureADServicePrincipal -Filter "AppId eq '$($app.AppId)'").ObjectId ` # -ResourceId $graphServicePrincipal.ObjectId ` # -Id $directoryReadAllPermission.Id ` # -PrincipalId (Get-AzureADServicePrincipal -Filter "AppId eq '$($app.AppId)'").ObjectId # ----------------------------------------------------------------------------------- #Print the App-ID, tenant ID, and client secret Write-Host "App-ID: $($app.AppId)" Write-Host "Tenant ID: $tenantId" Write-Host "Client Secret: $($secret.Value)"
关键说明
- 本次添加的是应用权限,适用于后台服务无需用户交互的场景
- 若未执行脚本中的管理员同意命令,需登录Azure门户手动完成权限批准操作
- 可通过
Get-AzureADApplicationAppRoleAssignment -ObjectId $app.ObjectId命令验证已分配的权限
内容的提问来源于stack exchange,提问作者Mr. Annonymous
相关产品推荐
相关产品推荐

