Setup/Test-STMGrantedPermissions.ps1
|
<#
.SYNOPSIS Read-only check of what an app registration can really do in Microsoft Graph for Intune. .DESCRIPTION Part 1 (app sign-in): asks for the client secret (hidden, kept in memory only), gets an app-only token straight from Microsoft Entra ID, shows the tenant, app id and the application permissions ("roles") inside that token, then tries one read per Intune area and shows pass or fail with Microsoft's error. Part 2 (optional, -CheckGrants): signs you in as yourself (needs Application.Read.All, for example Global Reader or Cloud Application Administrator) and lists what is actually granted to the app in this tenant: application permissions with admin consent, delegated consents, and what the app registration asks for. This shows why a token has no roles. Every call is a GET (plus the token request). Nothing is changed. The secret and the token are never printed or saved. .EXAMPLE .\Test-STMGrantedPermissions.ps1 -TenantId <tenant id> -ClientId <app id> .EXAMPLE .\Test-STMGrantedPermissions.ps1 -TenantId <tenant id> -ClientId <app id> -CheckGrants #> [CmdletBinding()] param( [Parameter(Mandatory)][string]$TenantId, [Parameter(Mandatory)][string]$ClientId, [switch]$CheckGrants, [switch]$SkipAppToken ) $ErrorActionPreference = 'Stop' [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 $graph = 'https://graph.microsoft.com' $need = 'DeviceManagementRBAC.Read.All', 'DeviceManagementConfiguration.Read.All', 'DeviceManagementApps.Read.All', 'DeviceManagementManagedDevices.Read.All', 'DeviceManagementServiceConfig.Read.All', 'DeviceManagementScripts.Read.All' function Get-Claims([string]$Jwt) { $p = $Jwt.Split('.')[1].Replace('-', '+').Replace('_', '/') switch ($p.Length % 4) { 2 { $p += '==' } 3 { $p += '=' } } [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($p)) | ConvertFrom-Json } function Get-GraphError($Err) { $code = ''; $msg = $Err.Exception.Message $body = '' if ($Err.ErrorDetails -and $Err.ErrorDetails.Message) { $body = $Err.ErrorDetails.Message } elseif ($Err.Exception.Response -and $Err.Exception.Response.GetResponseStream) { try { $body = (New-Object IO.StreamReader($Err.Exception.Response.GetResponseStream())).ReadToEnd() } catch { } } if ($body) { try { $j = $body | ConvertFrom-Json if ($j.error) { $code = if ($j.error.code) { [string]$j.error.code } else { [string]$j.error } $msg = if ($j.error.message) { [string]$j.error.message } elseif ($j.error_description) { [string]$j.error_description } else { $msg } if ($msg.TrimStart().StartsWith('{')) { try { $m = $msg | ConvertFrom-Json; if ($m.ErrorCode) { $code = $m.ErrorCode } } catch { } } } } catch { } } $status = '' try { $status = [int]$Err.Exception.Response.StatusCode } catch { } if ($msg.Length -gt 220) { $msg = $msg.Substring(0, 220) + '...' } [pscustomobject]@{ Status = $status; Code = $code; Message = ($msg -replace '\s+', ' ') } } function Write-Line($Label, $Value, $Color = 'Gray') { Write-Host ('{0,-26}' -f $Label) -NoNewline; Write-Host $Value -ForegroundColor $Color } Write-Host '' Write-Host 'Intune permission check (read-only)' -ForegroundColor Cyan Write-Line 'Tenant' $TenantId Write-Line 'App (client) id' $ClientId if (-not $SkipAppToken) { Write-Host '' Write-Host '== Part 1: app sign-in with the client secret ==' -ForegroundColor Cyan $sec = Read-Host -Prompt 'Client secret value (hidden, not saved)' -AsSecureString $plain = [System.Net.NetworkCredential]::new('', $sec).Password $token = $null try { $form = @{ client_id = $ClientId; client_secret = $plain; scope = "$graph/.default"; grant_type = 'client_credentials' } $resp = Invoke-RestMethod -Method POST -Uri "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token" -Body $form -ContentType 'application/x-www-form-urlencoded' $token = $resp.access_token } catch { $e = Get-GraphError $_ Write-Line 'Token request' "FAILED $($e.Status) $($e.Code): $($e.Message)" 'Red' Write-Host 'AADSTS7000215 = wrong secret value; AADSTS7000222 = secret expired; AADSTS700016 = app not found in this tenant.' -ForegroundColor Yellow } finally { $plain = $null; $form = $null; $sec.Dispose() } if ($token) { $c = Get-Claims $token $roles = @($c.roles | Where-Object { $_ } | Sort-Object) Write-Line 'Token request' 'OK' 'Green' Write-Line 'Token tenant' $c.tid Write-Line 'Token app id' $c.appid Write-Line 'Token app name' $c.app_displayname if ($c.tid -ne $TenantId) { Write-Line 'WARNING' 'token tenant is not the tenant you typed' 'Yellow' } if ($c.appid -ne $ClientId) { Write-Line 'WARNING' 'token app id is not the client id you typed' 'Yellow' } Write-Line 'Application permissions' $(if ($roles.Count) { $roles -join ', ' } else { '(none)' }) $(if ($roles.Count) { 'Green' } else { 'Red' }) $miss = @($need | Where-Object { $roles -notcontains $_ -and $roles -notcontains ($_ -replace 'Read\.All$', 'ReadWrite.All') }) Write-Line 'Intune read permissions' $(if ($miss.Count) { 'MISSING ' + ($miss -join ', ') } else { 'all present' }) $(if ($miss.Count) { 'Red' } else { 'Green' }) Write-Host '' Write-Host 'One read per Intune area:' -ForegroundColor Cyan $tests = [ordered]@{ 'Scope tags' = 'beta/deviceManagement/roleScopeTags?$top=1' 'Configuration profiles' = 'beta/deviceManagement/deviceConfigurations?$top=1&$select=id' 'Compliance policies' = 'beta/deviceManagement/deviceCompliancePolicies?$top=1&$select=id' 'Apps' = 'beta/deviceAppManagement/mobileApps?$top=1&$select=id' 'Managed devices' = 'beta/deviceManagement/managedDevices?$top=1&$select=id' 'Scripts' = 'beta/deviceManagement/deviceManagementScripts?$top=1&$select=id' 'Enrollment' = 'beta/deviceManagement/deviceEnrollmentConfigurations?$top=1&$select=id' 'Groups (names, optional)' = 'v1.0/groups?$top=1&$select=id' } $h = @{ Authorization = "Bearer $token" } foreach ($k in $tests.Keys) { try { [void](Invoke-RestMethod -Method GET -Uri "$graph/$($tests[$k])" -Headers $h); Write-Line $k 'PASS' 'Green' } catch { $e = Get-GraphError $_; Write-Line $k "FAIL $($e.Status) $($e.Code) $($e.Message)" 'Red' } } $token = $null; $h = $null } } if ($CheckGrants) { Write-Host '' Write-Host '== Part 2: what is granted to this app in the tenant (signed in as you) ==' -ForegroundColor Cyan if (-not (Get-Module -ListAvailable -Name Microsoft.Graph.Authentication)) { throw 'Install-Module Microsoft.Graph.Authentication -Scope CurrentUser first.' } Import-Module Microsoft.Graph.Authentication Connect-MgGraph -TenantId $TenantId -Scopes 'Application.Read.All' -NoWelcome -ContextScope Process | Out-Null try { $sp = @((Invoke-MgGraphRequest -Method GET -Uri "v1.0/servicePrincipals?`$filter=appId eq '$ClientId'&`$select=id,displayName,appId,appOwnerOrganizationId,accountEnabled" -OutputType PSObject).value) if (-not $sp.Count) { Write-Line 'Enterprise app' 'NOT FOUND in this tenant: the app has never been consented here' 'Red' } else { $sp = $sp[0] Write-Line 'Enterprise app' $sp.displayName Write-Line 'Enabled' $sp.accountEnabled $(if ($sp.accountEnabled) { 'Green' } else { 'Red' }) Write-Line 'Owner tenant' $(if ($sp.appOwnerOrganizationId -eq $TenantId) { 'this tenant' } else { "another tenant ($($sp.appOwnerOrganizationId))" }) $gsp = @((Invoke-MgGraphRequest -Method GET -Uri "v1.0/servicePrincipals?`$filter=appId eq '00000003-0000-0000-c000-000000000000'&`$select=id,appRoles,oauth2PermissionScopes" -OutputType PSObject).value)[0] $roleName = @{}; foreach ($r in $gsp.appRoles) { $roleName[[string]$r.id] = $r.value } $ara = @((Invoke-MgGraphRequest -Method GET -Uri "v1.0/servicePrincipals/$($sp.id)/appRoleAssignments" -OutputType PSObject).value | Where-Object { $_.resourceId -eq $gsp.id }) $granted = @($ara | ForEach-Object { $roleName[[string]$_.appRoleId] } | Sort-Object) Write-Line 'Application, consented' $(if ($granted.Count) { $granted -join ', ' } else { '(none)' }) $(if ($granted.Count) { 'Green' } else { 'Red' }) $dg = @((Invoke-MgGraphRequest -Method GET -Uri "v1.0/oauth2PermissionGrants?`$filter=clientId eq '$($sp.id)'" -OutputType PSObject).value | Where-Object { $_.resourceId -eq $gsp.id }) $del = @($dg | ForEach-Object { ([string]$_.scope).Split(' ') } | Where-Object { $_ } | Sort-Object -Unique) Write-Line 'Delegated, consented' $(if ($del.Count) { $del -join ', ' } else { '(none)' }) $app = @((Invoke-MgGraphRequest -Method GET -Uri "v1.0/applications?`$filter=appId eq '$ClientId'&`$select=id,requiredResourceAccess" -OutputType PSObject).value) if (-not $app.Count) { Write-Line 'App registration' 'not in this tenant (cannot show what it asks for)' 'Yellow' } else { $scopeName = @{}; foreach ($s in $gsp.oauth2PermissionScopes) { $scopeName[[string]$s.id] = $s.value } $req = @($app[0].requiredResourceAccess | Where-Object { $_.resourceAppId -eq '00000003-0000-0000-c000-000000000000' } | ForEach-Object { $_.resourceAccess }) $reqApp = @($req | Where-Object { $_.type -eq 'Role' } | ForEach-Object { $roleName[[string]$_.id] } | Sort-Object) $reqDel = @($req | Where-Object { $_.type -eq 'Scope' } | ForEach-Object { $scopeName[[string]$_.id] } | Sort-Object) Write-Line 'Requested, application' $(if ($reqApp.Count) { $reqApp -join ', ' } else { '(none)' }) Write-Line 'Requested, delegated' $(if ($reqDel.Count) { $reqDel -join ', ' } else { '(none)' }) $notConsented = @($reqApp | Where-Object { $granted -notcontains $_ }) if ($notConsented.Count) { Write-Line 'Not yet consented' ($notConsented -join ', ') 'Red' } } } } catch { $e = Get-GraphError $_; Write-Line 'Grant check' "FAILED $($e.Status) $($e.Code): $($e.Message)" 'Red' } finally { Disconnect-MgGraph | Out-Null } } Write-Host '' Write-Host 'Why "full permission" can still give a token with no roles:' -ForegroundColor Cyan Write-Host ' - The permissions were added as Delegated, not Application. App sign-in only uses Application permissions.' Write-Host ' - Application permissions were added but "Grant admin consent" was not pressed in this tenant.' Write-Host ' - Consent was granted on another app, or in another tenant (a multi-tenant app needs consent in each tenant).' Write-Host ' - The secret belongs to a different app registration (check the token app id above).' Write-Host ' - The token was issued before consent: sign out of the tool and sign in again (tokens last up to 24 hours).' Write-Host '' |