Skip to content

Instantly share code, notes, and snippets.

@kewalaka
Last active April 10, 2025 02:05
Show Gist options
  • Save kewalaka/68f8181846b8d8110ad380b0344c8785 to your computer and use it in GitHub Desktop.
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.
<#
.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