Skip to content

Instantly share code, notes, and snippets.

@kewalaka
Last active April 10, 2025 07:38
Show Gist options
  • Save kewalaka/22cc2d1e67a3c28535433762a817759a to your computer and use it in GitHub Desktop.
Save kewalaka/22cc2d1e67a3c28535433762a817759a 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. It is a shorter form of https://gist.github.com/kewalaka/68f8181846b8d8110ad380b0344c8785
$umiSP = Get-MgServicePrincipal -Filter "DisplayName eq '$ManagedIdentityName'"
$listPermissionAssignments = Get-MgServicePrincipalAppRoleAssignment -ServicePrincipalId $umiSP.Id
Write-Output "Searching for roles for Managed Identity: '$($umiSP.DisplayName)'"
foreach ($assignment in $listPermissionAssignments) {
$resourceSP = Get-MgServicePrincipal -ServicePrincipalId $assignment.ResourceId
# Find the app role definition that matches the AppRoleId from the assignment
$appRole = $resourceSP.AppRoles | Where-Object { $_.Id -eq $assignment.AppRoleId }
Write-Output "Found: '$($appRole.Value)' on resource '$($resourceSP.DisplayName)'."
}
# Set parameters
$TenantId = "your-tenant-id"
$ManagedIdentityName = "id-deployment-identity"
$PermissionsToGrantToMI = @(
"Group.ReadWrite.All",
"Application.ReadWrite.OwnedBy",
"User.Read.All"
)
# end params
Connect-MgGraph `
-Scopes @("Application.ReadWrite.All", "AppRoleAssignment.ReadWrite.All") `
-TenantId $TenantId
$MSGraphAPIResourceId = "00000003-0000-0000-c000-000000000000" # This is the well-known resource ID for the MS Graph
$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
}
$permsToRemove = Get-MgServicePrincipalAppRoleAssignment -ServicePrincipalId $umiSP.Id
foreach ($perm in $permsToRemove){
Remove-MgServicePrincipalAppRoleAssignment `
-AppRoleAssignmentId $perm.id `
-ServicePrincipalId $umiSP.Id
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment