Grant Admin Consent for API permission in Managed Identity object in Azure

Unlike the SPNs (App Registration) in Azure, a manual Admin Consent can't be given to a Managed Identity object. We have to use the script to do that. Before creating the script, you need to find the below details:
  • TenantID: Go to Azure Active Directory and in Overview, you will find the Tenant ID.
  • GraphAppID: It's the ID for different types of APIs, such as Microsoft Graph. Most of the time we use Microsoft Graph and its ID is 00000003-0000-0000-c000-000000000000. You can find IDs for commonly used Microsoft apps here.
  • DisplayNameofMSI: Give the name same as your app.
  • PermissionName: API permission you need on your app, such as User.Read.All or Sites.Read.All etc. I am taking Directory.Read.All as an example in this script.
$TenantID="provide the tenant ID"
$GraphAppId = "00000003-0000-0000-c000-000000000000"

$DisplayNameOfMSI="provide the App name"

$PermissionName = "Directory.Read.All"

Install-Module AzureAD

Connect-AzureAD -TenantId $TenantID

$MSI = (Get-AzureADServicePrincipal -Filter "displayName eq '$DisplayNameOfMSI'")
Start-Sleep -Seconds 10

$GraphServicePrincipal = Get-AzureADServicePrincipal -Filter "appId eq '$GraphAppId'"

$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

Once you are done, it will give you confirmation. Then you can go to the app and see the API permission in the Permission tab.

Comments