Skip to content

Instantly share code, notes, and snippets.

@kitos9112
Last active June 20, 2023 08:36
Show Gist options
  • Save kitos9112/21aa57249cbf466605fdba9726d903f9 to your computer and use it in GitHub Desktop.
Save kitos9112/21aa57249cbf466605fdba9726d903f9 to your computer and use it in GitHub Desktop.
Idempotently Manages MS Graph Permissions for a Managed-Service Identity in Azure using Powershell
#------------------------------------------------------------
# DO NOT EDIT THIS SECTION
#------------------------------------------------------------
$GraphAppId = "00000003-0000-0000-c000-000000000000" # Don't change this.
$oGraphSpn = Get-AzADServicePrincipal -Filter "appId eq '$GraphAppId'"
#------------------------------------------------------------
#------------------------------------------------------------
# EDIT THIS SECTION
## 1. Enter the Display name of the MSI
$MsiName = "MY-MSI-DISPLAY-NAME"
## 2. Enter the permissions you want to grant to the MSI. All othe permissions not listed here will be removed.
$oPermissions = @(
'DeviceManagementConfiguration.Read.All',
'DeviceManagementManagedDevices.Read.All'
)
#------------------------------------------------------------
# 1. Retrieve the ID of the Managed-Service Identity (MSI) that you want to grant permissions to.
$oMsi = Get-AzADServicePrincipal -Filter "displayName eq '$MsiName'"
# 2. List all Graph permissions we want to grant to the MSI.
## https://graphpermissions.merill.net/index.html
$oAppRoleIds = $oGraphSpn.AppRole | Where-Object {($_.Value -in $oPermissions) -and ($_.AllowedMemberType -contains "Application")} | forEach-Object {$_.Id}
# 3. Calculate the permissions we need to add or/and remove
$oAppRoleAssignedPermissions = Get-MgServicePrincipalAppRoleAssignment -ServicePrincipalId $oMsi.Id
$oAppRoleAssignedPermissionsIds = $oAppRoleAssignedPermissions | forEach-Object {$_.AppRoleId}
$oAppRoleAssignmentIdsAdd = Compare-Object $oAppRoleIds $oAppRoleAssignedPermissionsIds `
| Where-Object {$_.SideIndicator -eq '<='} | ForEach-Object {$_.InputObject}
$oAppRoleAssignmentIdsRemove = Compare-Object $oAppRoleAssignedPermissionsIds $oAppRoleIds `
| Where-Object {$_.SideIndicator -eq '<='} | ForEach-Object {$_.InputObject}
# 4. Grant the permissions to the MSI.
foreach($Id in $oAppRoleAssignmentIdsAdd)
{
$oAppRoleAssignment = @{
"PrincipalId" = $oMSI.Id
"ResourceId" = $oGraphSpn.Id
"AppRoleId" = $Id
}
$oAppRoleAssignment
New-MgServicePrincipalAppRoleAssignment `
-ServicePrincipalId $oAppRoleAssignment.PrincipalId `
-BodyParameter $oAppRoleAssignment `
-Verbose
}
# 5. Remove the permissions from the MSI.
foreach($Id in $oAppRoleAssignmentIdsRemove)
{
Remove-MgServicePrincipalAppRoleAssignment `
-ServicePrincipalId $oMsi.Id `
-AppRoleAssignmentId ($oAppRoleAssignedPermissions | Where-Object { $_.AppRoleId -eq $Id } | Select-Object -ExpandProperty Id) `
-Verbose
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment