Last active
April 10, 2025 02:05
-
-
Save kewalaka/68f8181846b8d8110ad380b0344c8785 to your computer and use it in GitHub Desktop.
This script grants specified Microsoft Graph API application permissions to a given user-assigned managed identity (UMI) by creating app role assignments.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
.SYNOPSIS | |
Assign Microsoft Graph API permissions to a user-assigned managed identity (UMI). | |
.DESCRIPTION | |
This script grants specified Microsoft Graph API application permissions to a given | |
user-assigned managed identity (UMI) by creating app role assignments. | |
.PARAMETER TenantId | |
The Entra (Azure AD) tenant ID where the managed identity resides. | |
.PARAMETER ManagedIdentityName | |
The display name of the managed identity to which permissions should be granted. | |
.PARAMETER AuthorisationScopes | |
The Graph scopes required to perform app role assignments (typically | |
"Application.ReadWrite.All" and "AppRoleAssignment.ReadWrite.All"). | |
.PARAMETER PermissionsToGrantToMI | |
The list of Graph API permissions to assign to the UMI (e.g., "Group.ReadWrite.All"). | |
.EXAMPLE | |
.\Grant-GraphPermissionsToUMI.ps1 ` | |
-TenantId "your-tenant-id" ` | |
-ManagedIdentityName "id-deployment-identity" ` | |
-PermissionsToGrantToMI @("Group.ReadWrite.All", "Application.ReadWrite.OwnedBy", "User.Read.All") | |
#> | |
param ( | |
[Parameter(Mandatory)] | |
[string]$TenantId, | |
[Parameter(Mandatory)] | |
[string]$ManagedIdentityName, | |
[Parameter()] | |
[string[]]$AuthorisationScopes = @("Application.ReadWrite.All", "AppRoleAssignment.ReadWrite.All"), | |
[Parameter()] | |
[string[]]$PermissionsToGrantToMI = @("Group.ReadWrite.All", "Application.ReadWrite.OwnedBy", "User.Read.All") | |
) | |
Connect-MgGraph -Scopes $AuthorisationScopes -TenantId $TenantId | |
$MSGraphAPIResourceId = "00000003-0000-0000-c000-000000000000" # This is the well-known resource ID for the MS Graph | |
# Lookup required IDs | |
$graphSP = Get-MgServicePrincipal -Filter "AppId eq '$MSGraphAPIResourceId'" | |
$permissions = $graphSP.AppRoles | Where-Object { $_.Value -in $PermissionsToGrantToMI } | |
$umiSP = Get-MgServicePrincipal -Filter "DisplayName eq '$ManagedIdentityName'" | |
foreach ($perm in $permissions) { | |
New-MgServicePrincipalAppRoleAssignment ` | |
-ServicePrincipalId $umiSP.Id ` | |
-PrincipalId $umiSP.Id ` | |
-ResourceId $graphSP.Id ` | |
-AppRoleId $perm.Id | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment