I'm trying to connect to Microsoft Graph using a User Managed Identity(UMI). I created the managed identity through the Azure portal, but now need to assign permissions like Users.Read.All and Group.Read.All to this identity using PowerShell so it can access user and group information.
I've found a script that uses the AzureAD module but as it is deprecating soon I want to transition to the Microsoft Graph PowerShell module where I need help with the equivalent commands.
Here's the old script I found:
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 provide guidance or a script to achieve this using the Microsoft Graph PowerShell module?
Assigning roles to your Managed Identity would look like this with the Graph API. The calls in this example are to:
If you want to use the cmdlets from the Microsoft.Graph.Applications
Module instead of direct API calls with Invoke-MgGraphRequest
, the cmdlets you need to use are Get-MgServicePrincipal
and New-MgServicePrincipalAppRoleAssignment
.
Connect-MgGraph ....
$Permissions = @(
'Group.Read.All',
'User.Read.All'
)
$NameOfMSI = 'my-managed-identity'
$msi = Invoke-MgGraphRequest GET "v1.0/servicePrincipals?`$filter=displayName eq '$NameOfMSI'"
$msiId = $msi.value[0]['id']
$GraphAppId = '00000003-0000-0000-c000-000000000000'
$GraphServicePrincipal = Invoke-MgGraphRequest GET "v1.0/servicePrincipals(appId='$GraphAppId')"
foreach ($role in $GraphServicePrincipal['appRoles']) {
if ($role['value'] -in $Permissions -and 'Application' -in $role['allowedMemberTypes']) {
Invoke-MgGraphRequest POST "v1.0/servicePrincipals/$msiId/appRoleAssignments" -Body @{
principalId = $msiId
resourceId = $GraphAppId
appRoleId = $role['id']
}
}
}