Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save astaykov/9f7325dad4715515c4cbd58e7343895a to your computer and use it in GitHub Desktop.
Save astaykov/9f7325dad4715515c4cbd58e7343895a to your computer and use it in GitHub Desktop.
# First, get the service principal object of the managed identity
# you can directly use the object, as it will be displayed on the managed identity properties
$miSP = Get-AzureADServicePrincipal -ObjectId 836955bf-0fe8-4b25-b1af-d1119558eec7
# second discover the service principal for the service you are looking to grant roles upon
# EXAMPLE: Microsoft Graph
# Note: the special GUID 00000003-0000-0000-c000-000000000000 is the application ID of Microsoft Graph
$resourceSP = Get-AzureADServicePrincipal -Filter "appId eq '00000003-0000-0000-c000-000000000000'"
# EXAMPLE Microsoft 365 Defender (Security Graph):
$resourceSP = Get-AzureADServicePrincipal -Filter "displayName eq 'Microsoft Threat Protection'"
# Define a list of application permissions you wish to grant
# for example, these are MS Graph Application permissions:
$appPermissions = @("Users.Read.All","Application.ReadWrite.OwnedBy")
# and these are Security Graph permissions (Microsoft 365 Defender API)
$appPermissions = @("SecurityAlert.Read.All","SecurityEvents.Read.All","SecurityIncident.Read.All")
# create an empty variable to collect the id (role id) of required permissions for consenting
$applicationPermissionsToGrant = @()
# loop through AppRoles property of the resource service principal (these are the Application permissions)
foreach($ap in $resourceSP.AppRoles)
{
if($ap.Value -in $appPermissions)
{
$applicationPermissionsToGrant += $ap.Id
}
}
# finally loop through the collected application roles (app permissions) and issue an Admin Concent.
# !!! NOTE !!!
# This action requires very high privileges - if it is MS Graph it requries Global Administrator
# If it is not MS Graph - this would require at least Application Administrator or Global Administrator
foreach($appRole in $applicationPermissionsToGrant)
{
New-AzureADServiceAppRoleAssignment `
-ObjectId $miSP.ObjectId `
-Id $appRole `
-PrincipalId $miSP.ObjectId `
-ResourceId $resourceSP.ObjectId
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment