Setup/New-STMAppRegistration.ps1

<#
.SYNOPSIS
  Creates or updates the app registration Intune Scope Tag Manager signs in with, and (optionally) grants tenant-wide admin consent.
 
.DESCRIPTION
  Run by a tenant admin. Needs: Application Administrator (or Cloud Application Administrator) to create or update the app,
  and Privileged Role Administrator or Global Administrator for -GrantAdminConsent.
 
  Permission sets:
    ReadOnly delegated read permissions only (viewing, exporting, building plans).
    ReadWrite ReadOnly plus delegated write permissions (applying plans, managing scope tags and role assignment scope tags). This is what admins who make changes need.
    Lab ReadWrite plus DeviceManagementRBAC.ReadWrite.All, used only by the lab test to create and delete its own test scope tags.
  -IncludeAppOnlyRead adds application (app-only) READ permissions for an unattended read-only inventory or permission check.
  The tool never writes with app-only access.
 
  Permission ids are looked up by name from the tenant's Microsoft Graph service principal, so nothing is hard-coded.
  Run with -WhatIf first to see exactly what would change.
 
.EXAMPLE
  .\New-STMAppRegistration.ps1 -TenantId <tenant-guid> -PermissionSet ReadWrite -WhatIf
.EXAMPLE
  .\New-STMAppRegistration.ps1 -TenantId <tenant-guid> -PermissionSet Lab -IncludeAppOnlyRead -GrantAdminConsent
.EXAMPLE
  .\New-STMAppRegistration.ps1 -TenantId <tenant-guid> -ExistingClientId <client-guid> -PermissionSet ReadWrite
#>

[CmdletBinding(SupportsShouldProcess)]
param(
    [Parameter(Mandatory)][string]$TenantId,
    [ValidateSet('ReadOnly', 'ReadWrite', 'Lab')][string]$PermissionSet = 'ReadWrite',
    [string]$DisplayName = 'Intune Scope Tag Manager',
    [string]$ExistingClientId,
    [switch]$IncludeGroupRead = $true,
    [switch]$IncludeAppOnlyRead,
    [switch]$GrantAdminConsent,
    [string]$AssignToGroupId,
    # Turns on "Allow public client flows". Only needed for device-code sign-in (-UseDeviceCode). Off by default, because it also
    # allows the resource-owner password grant for this app.
    [switch]$EnableDeviceCode
)
$ErrorActionPreference = 'Stop'
$graphAppId = '00000003-0000-0000-c000-000000000000'

$read = 'DeviceManagementConfiguration.Read.All', 'DeviceManagementApps.Read.All', 'DeviceManagementManagedDevices.Read.All', 'DeviceManagementServiceConfig.Read.All', 'DeviceManagementRBAC.Read.All', 'DeviceManagementScripts.Read.All'
$write = 'DeviceManagementConfiguration.ReadWrite.All', 'DeviceManagementApps.ReadWrite.All', 'DeviceManagementManagedDevices.ReadWrite.All', 'DeviceManagementServiceConfig.ReadWrite.All', 'DeviceManagementScripts.ReadWrite.All'
$delegated = @($read)
if ($PermissionSet -in 'ReadWrite', 'Lab') { $delegated += $write }
if ($PermissionSet -in 'ReadWrite', 'Lab') { $delegated += 'DeviceManagementRBAC.ReadWrite.All' }
if ($IncludeGroupRead) { $delegated += 'Group.Read.All' }
$application = @()
if ($IncludeAppOnlyRead) { $application = @($read); if ($IncludeGroupRead) { $application += 'Group.Read.All' } }

Write-Host "Delegated permissions: $($delegated -join ', ')"
if ($application) { Write-Host "Application permissions: $($application -join ', ')" }

$scopes = @('Application.ReadWrite.All')
if ($GrantAdminConsent) { $scopes += 'DelegatedPermissionGrant.ReadWrite.All', 'AppRoleAssignment.ReadWrite.All' }
if ($AssignToGroupId) { $scopes += 'AppRoleAssignment.ReadWrite.All' }
Import-Module Microsoft.Graph.Authentication
Connect-MgGraph -TenantId $TenantId -Scopes ($scopes | Sort-Object -Unique) -NoWelcome -ContextScope Process

function Invoke-G { param($Method, $Uri, $Body) if ($Body) { Invoke-MgGraphRequest -Method $Method -Uri "https://graph.microsoft.com/v1.0/$Uri" -Body ($Body | ConvertTo-Json -Depth 10) -ContentType 'application/json' } else { Invoke-MgGraphRequest -Method $Method -Uri "https://graph.microsoft.com/v1.0/$Uri" } }

$graphSp = (Invoke-G GET "servicePrincipals?`$filter=appId eq '$graphAppId'&`$select=id,oauth2PermissionScopes,appRoles").value[0]
$scopeIds = @{}; foreach ($s in $graphSp.oauth2PermissionScopes) { $scopeIds[$s.value] = $s.id }
$roleIds = @{}; foreach ($r in $graphSp.appRoles) { $roleIds[$r.value] = $r.id }
$access = @()
foreach ($p in ($delegated | Sort-Object -Unique)) { if (-not $scopeIds[$p]) { throw "Delegated permission $p not found on Microsoft Graph in this tenant" }; $access += @{ id = $scopeIds[$p]; type = 'Scope' } }
foreach ($p in ($application | Sort-Object -Unique)) { if (-not $roleIds[$p]) { throw "Application permission $p not found on Microsoft Graph in this tenant" }; $access += @{ id = $roleIds[$p]; type = 'Role' } }

if ($ExistingClientId) {
    $app = (Invoke-G GET "applications?`$filter=appId eq '$ExistingClientId'").value[0]
    if (-not $app) { throw "No app registration with client id $ExistingClientId" }
    # Keep every permission the app already has; add ours.
    $current = @($app.requiredResourceAccess | Where-Object { $_.resourceAppId -eq $graphAppId } | ForEach-Object { $_.resourceAccess }) 
    $merged = @($current | ForEach-Object { @{ id = $_.id; type = $_.type } }) + @($access | Where-Object { $a = $_; -not ($current | Where-Object { $_.id -eq $a.id -and $_.type -eq $a.type }) })
    $other = @($app.requiredResourceAccess | Where-Object { $_.resourceAppId -ne $graphAppId })
    $body = @{ requiredResourceAccess = @($other) + @(@{ resourceAppId = $graphAppId; resourceAccess = $merged }) }
    $added = $merged.Count - $current.Count
    if ($PSCmdlet.ShouldProcess("$($app.displayName) ($ExistingClientId)", "Add $added Microsoft Graph permission(s), keep the existing ones")) { Invoke-G PATCH "applications/$($app.id)" $body | Out-Null }
    # Sign-in from the tool needs the desktop redirects: http://localhost (browser) and the Windows sign-in broker.
    $want = @('http://localhost', "ms-appx-web://microsoft.aad.brokerplugin/$ExistingClientId")
    $have = @($app.publicClient.redirectUris)
    $missing = @($want | Where-Object { $have -notcontains $_ })
    if ($missing.Count -and $PSCmdlet.ShouldProcess("$($app.displayName) ($ExistingClientId)", "Add desktop sign-in redirect(s): $($missing -join ', ')")) {
        Invoke-G PATCH "applications/$($app.id)" @{ publicClient = @{ redirectUris = @($have + $missing) } } | Out-Null
    }
    if ($EnableDeviceCode -and -not $app.isFallbackPublicClient -and $PSCmdlet.ShouldProcess("$($app.displayName) ($ExistingClientId)", 'Allow public client flows (device code)')) {
        Invoke-G PATCH "applications/$($app.id)" @{ isFallbackPublicClient = $true } | Out-Null
    }
}
else {
    $body = @{
        displayName = $DisplayName; signInAudience = 'AzureADMyOrg'; isFallbackPublicClient = [bool]$EnableDeviceCode
        publicClient = @{ redirectUris = @('http://localhost') }
        requiredResourceAccess = @(@{ resourceAppId = $graphAppId; resourceAccess = $access })
        notes = 'Intune Scope Tag Manager: delegated sign-in for Intune admins; Intune RBAC and scope tags apply to every call.'
    }
    if ($PSCmdlet.ShouldProcess($DisplayName, 'Create single-tenant public client app registration')) {
        $app = Invoke-G POST 'applications' $body
        # Windows sign-in broker (WAM) redirect, used by Microsoft.Graph.Authentication on Windows.
        Invoke-G PATCH "applications/$($app.id)" @{ publicClient = @{ redirectUris = @('http://localhost', "ms-appx-web://microsoft.aad.brokerplugin/$($app.appId)") } } | Out-Null
    }
}
if (-not $app) { Write-Host 'WhatIf: nothing created.'; return }
$clientId = $app.appId

$sp = (Invoke-G GET "servicePrincipals?`$filter=appId eq '$clientId'").value[0]
if (-not $sp -and $PSCmdlet.ShouldProcess($clientId, 'Create service principal (enterprise app)')) {
    $sp = Invoke-G POST 'servicePrincipals' @{ appId = $clientId; appRoleAssignmentRequired = [bool]$AssignToGroupId; tags = @('WindowsAzureActiveDirectoryIntegratedApp') }
}
if ($AssignToGroupId -and $sp -and $PSCmdlet.ShouldProcess($AssignToGroupId, 'Require assignment and allow only this group to sign in')) {
    Invoke-G PATCH "servicePrincipals/$($sp.id)" @{ appRoleAssignmentRequired = $true } | Out-Null
    Invoke-G POST "servicePrincipals/$($sp.id)/appRoleAssignedTo" @{ principalId = $AssignToGroupId; resourceId = $sp.id; appRoleId = '00000000-0000-0000-0000-000000000000' } | Out-Null
}
if ($GrantAdminConsent -and $sp) {
    $scopeString = ($delegated | Sort-Object -Unique) -join ' '
    $existing = (Invoke-G GET "oauth2PermissionGrants?`$filter=clientId eq '$($sp.id)' and resourceId eq '$($graphSp.id)' and consentType eq 'AllPrincipals'").value | Select-Object -First 1
    if ($existing) {
        $union = (@($existing.scope -split ' ') + @($delegated) | Where-Object { $_ } | Sort-Object -Unique) -join ' '
        if ($PSCmdlet.ShouldProcess($clientId, "Update tenant-wide consent: $union")) { Invoke-G PATCH "oauth2PermissionGrants/$($existing.id)" @{ scope = $union } | Out-Null }
    }
    elseif ($PSCmdlet.ShouldProcess($clientId, "Grant tenant-wide consent: $scopeString")) {
        Invoke-G POST 'oauth2PermissionGrants' @{ clientId = $sp.id; consentType = 'AllPrincipals'; resourceId = $graphSp.id; scope = $scopeString } | Out-Null
    }
    foreach ($p in ($application | Sort-Object -Unique)) {
        $have = (Invoke-G GET "servicePrincipals/$($sp.id)/appRoleAssignments").value | Where-Object { $_.appRoleId -eq $roleIds[$p] }
        if (-not $have -and $PSCmdlet.ShouldProcess($clientId, "Grant application permission $p")) {
            Invoke-G POST "servicePrincipals/$($sp.id)/appRoleAssignments" @{ principalId = $sp.id; resourceId = $graphSp.id; appRoleId = $roleIds[$p] } | Out-Null
        }
    }
}
[pscustomobject]@{ TenantId = $TenantId; ClientId = $clientId; DisplayName = $app.displayName; Delegated = ($delegated -join ', '); Application = ($application -join ', '); AdminConsent = [bool]$GrantAdminConsent }
Write-Host "Done. Give the admins the tenant id and this client id; they type them once on the tool's sign-in screen." -ForegroundColor Green