$myApiSp = Get-MgServicePrincipal -Filter "displayName eq 'MultitenantApplication'"
# Or by AppId if displayName is not unique or known
# $myApiSp = Get-MgServicePrincipal -Filter "appId eq 'your-my-api-app-id'"
if (-not $myApiSp) {
Write-Error "Could not find Service Principal for 'My API Application Name'. Ensure it's correctly registered."
return
}
$externalAppSp = Get-MgServicePrincipal -Filter "displayName eq 'MultitenantApplication'"
# Or by AppId
# $externalAppSp = Get-MgServicePrincipal -Filter "appId eq 'external-multi-tenant-app-id'"
if (-not $externalAppSp) {
Write-Error "Could not find Service Principal for 'External Multi-Tenant App Name'. Ensure it has been consented to in your tenant."
return
}
# Get the App Roles (Application Permissions) exposed by My API
$myApiSp.AppRoles | Format-Table Id, DisplayName, Value, IsEnabled
# Pick the 'Id' of the specific scope you want to grant, e.g., for 'MyAPI.ReadData'
# For App Role (Application Permission)
$appRoleIdToGrant = ($myApiSp.AppRoles | Where-Object Value -eq "MyAPI.ReadData").Id
$params = @{
"principalId" = $externalAppSp.Id
"resourceId" = $myApiSp.Id
"appRoleId" = $appRoleIdToGrant # The ID of the app role you want to grant
}
New-MgServicePrincipalAppRoleAssignment -ServicePrincipalId $externalAppSp.Id -BodyParameter $params
Write-Host "Application permission granted for $($externalAppSp.DisplayName) to $($myApiSp.DisplayName) app role $($appRoleIdToGrant)."