azure-powershellazure-managed-identityazure-service-principalazure-identity

How to add Microsoft Graph permissions to managed identity service principal using Az PowerShell?


I'm working on connecting to Microsoft Graph using a User Managed Identity (UMI). I've already created the managed identity in the Azure portal, but now I need to assign permissions like User.Read.All and Group.Read.All to this identity using PowerShell to retrieve user and group information.

I previously asked a similar question and got solution using the Microsoft Graph PowerShell module here Grant access to managed identity service principal - Microsoft Graph PowerShell. However, now I need to achieve the same result using the Az PowerShell module.

Here’s the old script using the AzureAD module:


Connect-AzureAD



$TenantID = "TenantID"

$GraphAppId = "00000003-0000-0000-c000-000000000000"

$NameOfMSI = "my-managed-identity"

$Permissions = @("Group.Read.All", "User.Read.All")



$MSI = Get-AzureADServicePrincipal -Filter "displayName eq '$NameOfMSI'"

Start-Sleep -Seconds 10

$GraphServicePrincipal = Get-AzureADServicePrincipal -Filter "appId eq

'$GraphAppId'"



foreach ($PermissionName in $Permissions) {

    $AppRole = $GraphServicePrincipal.AppRoles | Where-Object {

        $_.Value -eq $PermissionName -and $_.AllowedMemberTypes

-contains "Application"

    }

    New-AzureAdServiceAppRoleAssignment -ObjectId $MSI.ObjectId

-PrincipalId $MSI.ObjectId -ResourceId $GraphServicePrincipal.ObjectId

-Id $AppRole.Id

}

Can anyone guide me on how to do this with the Az PowerShell module or is it possible at first?


Solution

  • To add Microsoft Graph permissions to managed identity service principal using Az PowerShell, make use of below sample script:

    Connect-AzAccount
    $GraphAppId = "00000003-0000-0000-c000-000000000000"
    $NameOfMSI = "testusermsi"
    $Permissions = @("Group.Read.All", "User.Read.All")
    
    $GraphServicePrincipal = Get-AzADServicePrincipal -AppId $GraphAppId
    
    foreach ($name in $Permissions) {
        $AppRole = $GraphServicePrincipal.AppRole | Where-Object {
            $_.Value -eq $name -and $_.Origin -contains "Application"
        }
    
        if ($AppRole) {
            try {
                New-AzADServicePrincipalAppRoleAssignment `
                    -ServicePrincipalDisplayName $NameOfMSI `
                    -ResourceDisplayName $GraphServicePrincipal.DisplayName `
                    -AppRoleId $AppRole.Id
            } catch {
                Write-Error "Failed to assign ${name}: $_"
            }
        }
    }
    

    Response:

    enter image description here

    To confirm that, I checked the same in Portal where permissions added successfully to service principal as below:

    enter image description here