Last active
June 6, 2024 05:30
-
-
Save marckean/9b69b0c6b9eaa2c9f66d6388370e32e5 to your computer and use it in GitHub Desktop.
This file contains 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
$UserAssignedManagedID_DisplayName = "TestMI" | |
#------------------------------------------------------------------------------ | |
# Install required modules | |
#------------------------------------------------------------------------------ | |
if (-not(Get-Module -ListAvailable -Name Az)) { | |
Install-Module -Name Az -Scope CurrentUser -AllowClobber -Force | |
Import-Module Az | |
} | |
if (-not(Get-Module -ListAvailable -Name Microsoft.Graph)) { | |
Install-Module -Name Microsoft.Graph -Scope CurrentUser -AllowClobber -Force | |
Import-Module Microsoft.Graph | |
} | |
#------------------------------------------------------------------------------ | |
# Connect to Azure & Entra | |
#------------------------------------------------------------------------------ | |
# Connect to Azure & MgGraph | |
Connect-AzAccount -UseDeviceAuthentication | |
Connect-MgGraph -Scopes "AppRoleAssignment.ReadWrite.All", "Application.Read.All" -UseDeviceCode | |
# Get the managed identity's ObjectId | |
$managedIdentity = Get-AzADServicePrincipal -DisplayName $UserAssignedManagedID_DisplayName | |
# Define the required Microsoft Graph API permissions | |
$graphSPN = Get-MgServicePrincipal -Filter "AppId eq '00000003-0000-0000-c000-000000000000'" | |
#-------------------------------------------------------------------- | |
# Set permissions - "User.Read.All", "Group.Read.All", "Group.ReadWrite.All", "Directory.Read.All" | |
#-------------------------------------------------------------------- | |
$permissions = @() | |
# Set permission scope | |
$permissions = @("User.Read.All", "Group.Read.All", "Group.ReadWrite.All", "Directory.Read.All") | |
foreach ($permission in $permissions) { | |
# Find app role with those permissions | |
$appRole = $graphSPN.AppRoles | | |
Where-Object Value -eq $permission | | |
Where-Object AllowedMemberTypes -contains "Application" | |
$bodyParam = @{ | |
PrincipalId = $managedIdentity.Id | |
ResourceId = $graphSPN.Id | |
AppRoleId = $appRole.Id | |
} | |
New-MgServicePrincipalAppRoleAssignment -ServicePrincipalId $managedIdentity.Id -BodyParameter $bodyParam | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment