How to Assign permissions to a Managed Identity

Page content

Assigning permissions to a Managed Identity is more complex than an app registration; the only way is thru PowerShell or Microsoft Graph. So this time, I created a simple script to add permissions to a Managed Identity using the Graph PowerShell modules.

Prerequisites

You need two modules for this:

  • Microsoft.Graph.Applications
  • Microsoft.Graph.Authentication

Rights

The rights that are needed to assign rights and find the correct IDs are

  • Directory.Read.All
  • AppRoleAssignment.ReadWrite.All

The script

$objectID = "<ObjectID of the Managed Identity>"
$ServicePrincipal = Get-MgServicePrincipal -Filter "AppId eq '00000003-0000-0000-c000-000000000000'"
$approle = $ServicePrincipal.AppRoles | Where-Object {$_.Value -eq "Sites.Selected" -and $_.AllowedMemberTypes -contains "Application"}
New-MgServicePrincipalAppRoleAssignment -ServicePrincipalId $objectID -PrincipalId $objectID -ResourceId $ServicePrincipal.Id -AppRoleId $appRole.Id

You need to find some Identifiers before assigning permission to the Managed Identity. In the above script, Microsoft.Graph application permission ‘sites.selected’ is given to the Managed Identity. The resourceId is the id of Microsoft.Graph ServicePrincipal.

References

Here are the references to the Microsoft documentation: