Skip to main content
Connectors

Bring your own Microsoft app registration: the provisioning script and permission tiers

The PowerShell script that registers your organization's own multitenant Entra app for the Microsoft Graph and Azure connectors, the redirect URLs it registers, and the delegated permission list for the Full, Standard and Read-only tiers.

Written By Christopher Scaminaci

Last updated 5 days ago

Some organizations prefer to consent to an application they own: their name on the consent screen, their control over the permission list, their secret to rotate. StackJack supports that for its Microsoft connectors: Microsoft Graph, Microsoft Azure, Microsoft Defender for Endpoint, Microsoft Exchange Online, Microsoft Purview, Microsoft SharePoint Admin, Microsoft Teams Admin and Microsoft Power Platform Admin. This page carries the provisioning script and the delegated permission list for each tier.

What the script does

Run it signed in to your own Entra tenant as a Global Administrator or Application Administrator. It creates a multitenant app registration that carries StackJack's redirect URLs (Web platform), requests the delegated permission set for the tier you pick, lists the Partner Center API permission user_impersonation when your tenant has the Microsoft Partner Center application (only Authorize all customers and the Partner Center billing tools use it), lists the Microsoft Partner API permission in that same tenant (only the Partner Center price sheet of an AI Deploy and Manage purchase uses it; -SkipPartnerCenter leaves both out), lists the WindowsDefenderATP delegated permissions when your tenant has that application (only the Microsoft Defender for Endpoint connector uses them; pass -SkipDefenderForEndpoint to leave them out), lists the permissions of the Microsoft Exchange Online, Microsoft Purview, Microsoft SharePoint Admin, Microsoft Teams Admin and Microsoft Power Platform Admin connectors (each has its own switch that leaves it out), and prints the Application (client) ID and a client secret once at the end. Paste those into StackJack under Connectors, on the Microsoft connector you are setting up, Advanced, use your own app registration, then use Connect with Microsoft.

Prerequisites

  • PowerShell 7 with the Az.Accounts module (Install-Module Az.Accounts).
  • Connect-AzAccount -TenantId <your tenant id> as Global Administrator or Application Administrator.
  • Your StackJack Portal host: portal.stackjack.io for the US region, portal-eu.stackjack.io for the EU region.

Run it

.\provision-byo-microsoft-appreg.ps1 -PortalHost portal.stackjack.io -PermissionTier Full

Parameters: -PortalHost (required), -PermissionTier Full | Standard | Read (default Full), -DisplayName (default "StackJack Connector"), -AppId (update an existing registration instead of creating one), -SecretYears (1 to 5, default 2), -SkipPartnerCenter, -SkipDefenderForEndpoint, -SkipExchangeOnline, -SkipPurview, -SkipSharePointAdmin, -SkipTeamsAdmin and -SkipPowerPlatform (leave those permissions out).

The registration carries these redirect URLs for the US region (replace the host for the EU region):

  • https://portal.stackjack.io/connector-callback/msgraph
  • https://portal.stackjack.io/connector-callback/azure
  • https://portal.stackjack.io/connector-callback/defenderendpoint
  • https://portal.stackjack.io/connector-callback/exchangeonline
  • https://portal.stackjack.io/connector-callback/purview
  • https://portal.stackjack.io/connector-callback/sharepointadmin
  • https://portal.stackjack.io/connector-callback/teamsadmin
  • https://portal.stackjack.io/connector-callback/powerplatform
  • https://portal.stackjack.io/consent-complete

The last one is required: the per-customer-tenant consent links StackJack generates for GDAP need it, or Microsoft answers with a reply-address error.

Notes on the -AppId update path. The update adds the redirect URLs for the -PortalHost you pass and keeps every Web redirect URL already registered on the app, so you can run it once per Portal host your organization signs in to, and it is safe on an app that carries redirect URLs of your own. Three things are not additive: a re-run adds a new client secret next to the old one (remove superseded secrets in the Entra portal), the requested permission list is replaced with the -PermissionTier you pass, and the display name is replaced with -DisplayName (pass the app's current name to keep it).

The script

Save the block below as provision-byo-microsoft-appreg.ps1.

#Requires -Modules Az.Accounts
<#
.SYNOPSIS
    Creates YOUR ORGANIZATION'S OWN Entra app registration for the StackJack Microsoft Graph and
    Azure connectors ("bring your own app registration", 2026-08-26).

.DESCRIPTION
    Run this signed in (Connect-AzAccount) to YOUR OWN Entra tenant as a Global Administrator or
    Application Administrator. It creates a MULTITENANT app registration that:
      - carries StackJack's redirect URLs (Web platform), so StackJack's connect flow can
        complete against your app;
      - requests the delegated permission set for the tier you choose (Full | Standard | Read) —
        the same tiers StackJack's connect flow offers;
      - if your Microsoft Entra tenant has the Microsoft Partner Center application (a Cloud
        Solution Provider partner tenant normally does), also lists the Partner Center API
        permission user_impersonation. Only
        "Authorize all customers" and the Partner Center billing tools use it. Listing it does not
        grant it: an administrator in your tenant still approves it once. Skip it with
        -SkipPartnerCenter;
      - does NOT list the Microsoft Partner API permission (the Partner Center price sheet of an AI Deploy and
        Manage purchase). A customer directory that is not a partner has no service principal for it, and
        Microsoft then refuses every admin consent for your app in that directory with AADSTS650052. A re-run
        with -AppId REPLACES the app's permission list, so a re-run removes it from an app an earlier run
        listed it on;
      - gets a client secret, printed ONCE at the end.

    Paste the printed Application (client) ID and client secret into StackJack under
    Connectors → Microsoft Graph (or Microsoft Azure) → "Advanced — use your own app
    registration", then use Connect with Microsoft. Deploying via automation: this script IS the
    automation — run it from any pipeline that can Connect-AzAccount; a CIPP app-deployment
    template can apply the same manifest values.

    The permission lists below match what StackJack's connect flow asks for, as of 2026-08-26. If
    StackJack adds permissions later, re-run this script (it PATCHes the existing app when -AppId
    is supplied) or approve the new permissions on the next consent prompt.

.PARAMETER PortalHost
    The StackJack Portal host your organization signs into (no scheme), e.g. portal.example.com.
    StackJack's redirect URLs are registered under it: the sign-in callbacks of the Microsoft Graph, Azure,
    Microsoft Defender for Endpoint, Exchange Online, Purview, SharePoint admin, Teams admin and Power Platform connectors, and the consent landing page. If your people sign in
    to more than one StackJack region, run the script again with -AppId and the other Portal host:
    the second run ADDS that host's URLs and keeps the first host's.

.PARAMETER PermissionTier
    Full (default) — every capability. Standard — everything except directory-privileged writes
    (their read-only forms are still requested). Read — the read-only form of every capability the
    connector ships.

.PARAMETER DisplayName
    The app registration's display name. Default: "StackJack Connector".

.PARAMETER AppId
    Optional: an existing app registration (client id) to UPDATE instead of creating a new one.
    The update ADDS the StackJack redirect URLs for this -PortalHost and KEEPS every Web
    redirect URL already registered on the app, so it is safe to run once per Portal host your
    organization signs in to, and safe on an app that carries redirect URLs of your own.
    Three update-path behaviors that are NOT additive, so that you can plan for them: a re-run
    ADDS a new client secret alongside the old one (remove superseded secrets in the Entra
    portal), the requested permission list is REPLACED with the -PermissionTier set you pass, and
    the display name is REPLACED with -DisplayName (pass the app's current name to keep it).

.PARAMETER SkipDefenderForEndpoint
    Do not list the WindowsDefenderATP permissions. Use it when this app will never run the Microsoft Defender for Endpoint connector. A re-run with -AppId REPLACES the app's permission
    list, so a re-run with this switch removes them.

.PARAMETER SkipPurview
    Do not list the Microsoft Purview delegated permission (the Security and Compliance PowerShell cmdlet API and its content search session). Use it when this app will never run the Microsoft Purview connector.
    The script finds those two Microsoft services by the resource URL each carries and lists a permission only when the service itself publishes it; a tenant where it finds none lists nothing and says so.
.PARAMETER SkipExchangeOnline
    Do not list the Office 365 Exchange Online permission (Exchange.Manage). Use it when this app will never run the Microsoft Exchange Online connector. A re-run with -AppId REPLACES the app's permission
    list, so a re-run with this switch removes it.
.PARAMETER SkipTeamsAdmin
    Do not list the Skype and Teams Tenant Admin API permission (user_impersonation). Use it when this app will never run the Microsoft Teams Admin connector. A re-run with -AppId REPLACES the app's
    permission list, so a re-run with this switch removes it.
.PARAMETER SkipPowerPlatform
    Do not list the Power Platform permissions (the Power Platform API's EnvironmentManagement.Environments.Read, EnvironmentManagement.Groups.Read, EnvironmentManagement.Groups.ReadWrite,
    EnvironmentManagement.Settings.Read, EnvironmentManagement.Settings.ReadWrite, Licensing.Allocations.Read, Licensing.BillingPolicies.Read and Licensing.BillingPolicies.ReadWrite, and the Power Apps Service's User). Use it when this app will never run the Microsoft Power Platform Admin connector. The script finds each service by its
    application id and lists a permission only when the service itself publishes it; a tenant where it finds none lists nothing and says so. A re-run with -AppId REPLACES the app's permission list, so a
    re-run with this switch removes them.
.PARAMETER SkipSharePointAdmin
    Do not list the SharePoint permissions (AllSites.FullControl on Office 365 SharePoint Online, and the two SharePoint tenant-settings permissions on Microsoft Graph). Use it when this app will never
    run the Microsoft SharePoint Admin connector. A re-run with -AppId REPLACES the app's permission list, so a re-run with this switch removes them.

.PARAMETER SkipPartnerCenter
    Do not list the Microsoft Partner Center API permission (user_impersonation). Use it when this app
    will never run "Authorize all customers" or the Partner Center billing tools. A re-run with
    -AppId REPLACES the app's permission list, so a re-run with this switch removes the Partner Center
    permission that an earlier run added.

.PARAMETER SecretYears
    Client-secret lifetime in years (default 2). You must rotate it in StackJack before it
    expires; users reconnect after a rotation.
#>
param(
    [Parameter(Mandatory)][string]$PortalHost,
    [ValidateSet('Full', 'Standard', 'Read')][string]$PermissionTier = 'Full',
    [string]$DisplayName = 'StackJack Connector',
    [string]$AppId,
    [switch]$SkipPartnerCenter,
    [switch]$SkipDefenderForEndpoint,
    [switch]$SkipExchangeOnline,
    [switch]$SkipPurview,
    [switch]$SkipSharePointAdmin,
    [switch]$SkipTeamsAdmin,
    [switch]$SkipPowerPlatform,
    [ValidateRange(1, 5)][int]$SecretYears = 2
)
$ErrorActionPreference = 'Stop'

function Invoke-Graph {
    param([string]$Method = 'GET', [Parameter(Mandatory)][string]$Uri, $Body)
    $p = @{ Method = $Method; Uri = $Uri }
    if ($null -ne $Body) { $p.Payload = ($Body | ConvertTo-Json -Depth 10) }
    $r = Invoke-AzRestMethod @p
    if ($r.StatusCode -ge 300) { throw "Graph $Method $Uri -> HTTP $($r.StatusCode): $($r.Content)" }
    if ($r.Content) { return ($r.Content | ConvertFrom-Json) }
}

function Get-ResourceSp {
    param([Parameter(Mandatory)][string]$WellKnownAppId)
    $f = [uri]::EscapeDataString("appId eq '$WellKnownAppId'")
    $sp = (Invoke-Graph -Uri "https://graph.microsoft.com/v1.0/servicePrincipals?`$filter=$f&`$select=id,appId,displayName,oauth2PermissionScopes").value | Select-Object -First 1
    if (-not $sp) {
        Write-Host "Service principal for appId $WellKnownAppId not present in tenant - instantiating it."
        Invoke-Graph -Method POST -Uri 'https://graph.microsoft.com/v1.0/servicePrincipals' -Body @{ appId = $WellKnownAppId } | Out-Null
        Start-Sleep -Seconds 5
        $sp = (Invoke-Graph -Uri "https://graph.microsoft.com/v1.0/servicePrincipals?`$filter=$f&`$select=id,appId,displayName,oauth2PermissionScopes").value | Select-Object -First 1
    }
    if (-not $sp) { throw "Could not resolve service principal (appId='$WellKnownAppId')." }
    return $sp
}

# ---- Canonical Graph roster (transcribed 2026-08-26; MUST track BuildMicrosoftScope) ----
$graphScopesFull = @(
    'openid'; 'profile'; 'email'; 'offline_access'
    'User.Read'; 'User.ReadWrite.All'; 'Group.ReadWrite.All'; 'Directory.ReadWrite.All'
    'AdministrativeUnit.ReadWrite.All'; 'AppRoleAssignment.ReadWrite.All'
    'Directory.AccessAsUser.All'
    'Device.Read.All'; 'Application.ReadWrite.All'; 'RoleManagement.ReadWrite.Directory'
    'Policy.Read.All'; 'Policy.ReadWrite.ConditionalAccess'; 'Policy.ReadWrite.AuthenticationMethod'
    'Policy.ReadWrite.MobilityManagement'
    'AuditLog.Read.All'; 'Reports.Read.All'; 'Organization.ReadWrite.All'; 'Domain.ReadWrite.All'
    'IdentityRiskyUser.ReadWrite.All'; 'IdentityRiskEvent.Read.All'
    'Mail.ReadWrite'; 'Mail.Send'; 'Calendars.ReadWrite'; 'Files.ReadWrite.All'; 'Sites.ReadWrite.All'
    'MailboxSettings.ReadWrite'
    'Contacts.ReadWrite'
    'Mail.ReadWrite.Shared'; 'Calendars.ReadWrite.Shared'; 'Contacts.ReadWrite.Shared'
    'Mail.Send.Shared'
    'Team.ReadBasic.All'; 'Channel.ReadBasic.All'; 'ChannelMessage.Read.All'; 'TeamMember.ReadWrite.All'
    'Team.Create'; 'TeamSettings.ReadWrite.All'; 'Channel.Create'; 'ChannelSettings.ReadWrite.All'
    'ChannelMessage.Send'; 'Chat.ReadWrite'; 'Presence.Read.All'
    'SecurityEvents.ReadWrite.All'; 'SecurityAlert.ReadWrite.All'; 'SecurityIncident.ReadWrite.All'
    'ThreatHunting.Read.All'; 'RecordsManagement.ReadWrite.All'; 'SensitivityLabel.Read'
    'DeviceManagementManagedDevices.PrivilegedOperations.All'
    'DeviceManagementManagedDevices.ReadWrite.All'
    'DeviceManagementConfiguration.ReadWrite.All'; 'DeviceManagementApps.ReadWrite.All'
    'DeviceManagementServiceConfig.ReadWrite.All'; 'DeviceManagementRBAC.Read.All'
    'DeviceManagementRBAC.ReadWrite.All'; 'DeviceManagementScripts.ReadWrite.All'
    'DelegatedAdminRelationship.ReadWrite.All'
    'UserAuthenticationMethod.ReadWrite.All'
    'ManagedTenants.ReadWrite.All'; 'CloudPC.ReadWrite.All'; 'AuditLogsQuery.Read.All'
    'ServiceHealth.Read.All'; 'ServiceMessage.Read.All'; 'ServiceMessageViewpoint.Write'
    'eDiscovery.ReadWrite.All'
    'Synchronization.ReadWrite.All'; 'CopilotPolicySettings.ReadWrite'; 'CopilotSettings-LimitedMode.ReadWrite'; 'CopilotPackages.ReadWrite.All'
    'CopilotCostManagement-Policy.ReadWrite.All'; 'CopilotCostManagement-Assignment.ReadWrite.All'; 'CopilotCostManagement-UserData.Read.All'
    'CopilotCostManagement-CreditReq.ReadWrite.All'; 'CopilotCostManagement.Read.All'
)
if ($graphScopesFull.Count -ne 78) { throw 'Scope transcription drift - expected 78 Graph scopes.' }

# MUST mirror MicrosoftScopeTier.StandardTierRemovals.
$standardRemovals = @(
    'Directory.AccessAsUser.All'
    'RoleManagement.ReadWrite.Directory'
    'Application.ReadWrite.All'
    'AppRoleAssignment.ReadWrite.All'
    'Policy.ReadWrite.ConditionalAccess'
    'Policy.ReadWrite.AuthenticationMethod'
    'Policy.ReadWrite.MobilityManagement'
    'UserAuthenticationMethod.ReadWrite.All'
    'IdentityRiskyUser.ReadWrite.All'
    'DeviceManagementManagedDevices.PrivilegedOperations.All'
    'Domain.ReadWrite.All'
    'Organization.ReadWrite.All'
    'DelegatedAdminRelationship.ReadWrite.All'
)
# MUST mirror MicrosoftScopeTier.StandardTierReadBackfill.
$standardReadBackfill = @(
    'RoleManagement.Read.Directory'; 'Application.Read.All'
    'UserAuthenticationMethod.Read.All'; 'IdentityRiskyUser.Read.All'
    'Domain.Read.All'; 'Organization.Read.All'; 'DelegatedAdminRelationship.Read.All'
)
# MUST mirror MicrosoftScopeTier's read-tier output over the canonical roster (transcribed 2026-08-26).
$graphScopesRead = @(
    'openid'; 'profile'; 'email'; 'offline_access'; 'User.Read'
    'User.Read.All'; 'Group.Read.All'; 'Directory.Read.All'; 'AdministrativeUnit.Read.All'
    'Device.Read.All'; 'Application.Read.All'; 'RoleManagement.Read.Directory'
    'Policy.Read.All'; 'AuditLog.Read.All'; 'Reports.Read.All'
    'Organization.Read.All'; 'Domain.Read.All'
    'IdentityRiskyUser.Read.All'; 'IdentityRiskEvent.Read.All'
    'Mail.Read'; 'Calendars.Read'; 'Files.Read.All'; 'Sites.Read.All'
    'MailboxSettings.Read'; 'Contacts.Read'
    'Mail.Read.Shared'; 'Calendars.Read.Shared'; 'Contacts.Read.Shared'
    'Team.ReadBasic.All'; 'Channel.ReadBasic.All'; 'ChannelMessage.Read.All'
    'TeamMember.Read.All'; 'TeamSettings.Read.All'; 'ChannelSettings.Read.All'
    'Chat.Read'; 'Presence.Read.All'
    'SecurityEvents.Read.All'; 'SecurityAlert.Read.All'; 'SecurityIncident.Read.All'
    'ThreatHunting.Read.All'; 'RecordsManagement.Read.All'; 'SensitivityLabel.Read'
    'DeviceManagementManagedDevices.Read.All'; 'DeviceManagementConfiguration.Read.All'
    'DeviceManagementApps.Read.All'; 'DeviceManagementServiceConfig.Read.All'
    'DeviceManagementRBAC.Read.All'
    'DelegatedAdminRelationship.Read.All'; 'UserAuthenticationMethod.Read.All'
    'ManagedTenants.Read.All'; 'CloudPC.Read.All'; 'AuditLogsQuery.Read.All'
    'ServiceHealth.Read.All'; 'ServiceMessage.Read.All'; 'eDiscovery.Read.All'
    'Synchronization.Read.All'; 'CopilotPolicySettings.Read'; 'CopilotSettings-LimitedMode.Read'; 'CopilotPackages.Read.All'
    'CopilotCostManagement-Policy.Read.All'; 'CopilotCostManagement-Assignment.Read.All'; 'CopilotCostManagement-UserData.Read.All'
    'CopilotCostManagement-CreditReq.Read.All'; 'CopilotCostManagement.Read.All'
)

$graphScopes = switch ($PermissionTier) {
    'Full'     { $graphScopesFull }
    'Standard' { @($graphScopesFull | Where-Object { $_ -notin $standardRemovals }) + $standardReadBackfill }
    'Read'     { $graphScopesRead }
}
# Not "N of 62" - a narrower tier is not a subset. Read and Standard both request read-only forms
# of capabilities that Full requests only as writes, so their counts are not drawn from Full's list.
Write-Host "Tier '$PermissionTier': requesting $(@($graphScopes).Count) Graph permissions (Full requests $($graphScopesFull.Count))."

# ---- Resolve resources + permission GUIDs ----
$graphSp = Get-ResourceSp -WellKnownAppId '00000003-0000-0000-c000-000000000000'   # Microsoft Graph
$armSp   = Get-ResourceSp -WellKnownAppId '797f4846-ba00-4fd7-ba43-dac1f8f63013'   # Azure Service Management

# ---- Partner Center API (optional) ----
# The Partner Center API is the resource https://api.partnercenter.microsoft.com, served by the first-party
# application "Microsoft Partner Center". Microsoft Learn names the resource URL and the delegated
# permission to request (User Impersonation) but prints only a placeholder for the application id, so this
# script does NOT carry the id. It finds the service principal in YOUR tenant by that resource URL, which
# is the identifier the Microsoft identity platform itself uses for the resource, and reads the permission
# id from the service principal's own oauth2PermissionScopes by its value, user_impersonation, the same way
# it resolves every other permission above.
#   Resource URL:           https://learn.microsoft.com/en-us/partner-center/developer/secure-app-model-framework
#   Service principal and   https://learn.microsoft.com/en-us/partner-center/developer/secure-sample-application
#   User Impersonation:
#   Filtering by URL:       https://learn.microsoft.com/en-us/graph/api/resources/serviceprincipal
#                           (servicePrincipalNames supports $filter with eq, through the any operator)
$partnerCenterResourceUri = 'https://api.partnercenter.microsoft.com'
$partnerCenterScopeName   = 'user_impersonation'

function Get-PartnerCenterSp {
    # $null when this tenant has no Microsoft Partner Center service principal. Never creates one: Learn
    # gives no application id to create it from, and a tenant without it is normally not a partner tenant.
    $f = [uri]::EscapeDataString("servicePrincipalNames/any(n:n eq '$partnerCenterResourceUri')")
    return (Invoke-Graph -Uri "https://graph.microsoft.com/v1.0/servicePrincipals?`$filter=$f&`$select=id,appId,displayName,oauth2PermissionScopes").value | Select-Object -First 1
}

function Get-PartnerCenterResourceAccess {
    # The requiredResourceAccess entry for the Partner Center API, or $null when the service principal is
    # missing or does not publish user_impersonation. $null means "leave it out", never "fail": a tenant
    # that is not a partner has nothing to list, and the rest of the app is still correct.
    #
    # It takes everything it needs through parameters and reads no script variable, so the Pester suite
    # can evaluate this function alone out of the file's syntax tree.
    param($Sp, [string]$ScopeName = 'user_impersonation')
    if (-not $Sp) { return $null }
    $scope = @($Sp.oauth2PermissionScopes) | Where-Object { $_.value -eq $ScopeName } | Select-Object -First 1
    if (-not $scope) { return $null }
    return @{ resourceAppId = $Sp.appId; resourceAccess = @(@{ id = $scope.id; type = 'Scope' }) }
}

# The Microsoft Partner API (the Partner Center price sheet of an AI Deploy and Manage purchase, https://api.partner.microsoft.com) is deliberately NOT listed here (2026-11-14, Featurebase #583). This script listed it from
# 2026-11-10 and created its service principal in your tenant, but a customer directory that is not a partner has no service principal for it, and Microsoft then refuses EVERY admin consent for the app in that directory
# with AADSTS650052, even a link scoped to Graph alone. The price sheet stays off in StackJack until it has a partner-directory consent path with an explicit scope, so nothing needs the permission on the app.

# The Defender for Endpoint connector (2026-11-07). WindowsDefenderATP is found by its display name: this script carries no application id it did not read from Microsoft Learn for this resource,
# and it never creates the service principal, because a tenant without Defender has nothing to list. The names include each spelling the reference prints; only the ones the service principal
# publishes are listed.
$defenderResourceName = 'WindowsDefenderATP'
$defenderScopeCandidates = @(
    'Machine.Read', 'Machine.ReadWrite', 'Machine.Isolate', 'Machine.RestrictExecution', 'Machine.Scan', 'Machine.CollectForensics',
    'Machine.StopAndQuarantine', 'Machine.LiveResponse', 'Machine.Offboard', 'Library.Manage',
    'Alert.Read', 'Alert.ReadWrite', 'AdvancedQuery.Read', 'Ti.ReadWrite', 'Ti.Read',
    'Score.Read', 'SecurityRecommendation.Read', 'Software.Read', 'Vulnerability.Read', 'SecurityBaselinesAssessment.Read',
    'RemediationTask.Read', 'RemediationTasks.Read',
    'File.Read', 'File.Read.All', 'Ip.Read', 'Ip.Read.All', 'Url.Read', 'Url.Read.All', 'URL.Read.All', 'User.Read', 'User.Read.All'
)

function Get-DefenderSp {
    # $null when this tenant has no WindowsDefenderATP service principal: normally a tenant with no Defender for Endpoint or Defender for Business.
    $f = [uri]::EscapeDataString("displayName eq '$defenderResourceName'")
    return (Invoke-Graph -Uri "https://graph.microsoft.com/v1.0/servicePrincipals?`$filter=$f&`$select=id,appId,displayName,oauth2PermissionScopes").value | Select-Object -First 1
}

function Get-DefenderResourceAccess {
    # The requiredResourceAccess entry for WindowsDefenderATP, or $null when the service principal is missing or publishes none of the names. $null means "leave it out", never "fail".
    # It takes everything it needs through parameters and reads no script variable, so the Pester suite can evaluate this function alone out of the file's syntax tree.
    param($Sp, [string[]]$ScopeNames)
    if (-not $Sp) { return $null }
    $scopes = @($Sp.oauth2PermissionScopes) | Where-Object { $ScopeNames -ccontains $_.value }
    if (-not @($scopes).Count) { return $null }
    return @{ resourceAppId = $Sp.appId; resourceAccess = @(@($scopes) | ForEach-Object { @{ id = $_.id; type = 'Scope' } }) }
}

# The Exchange Online connector (2026-11-08). Office 365 Exchange Online is found by its application id, which Microsoft Learn prints for it in the Exchange Online PowerShell pages
# (00000002-0000-0ff1-ce00-000000000000), and the script never creates the service principal, because a tenant with no Exchange Online has nothing to list. Exchange.Manage is the delegated permission
# Microsoft's GDAP page grants a partner application; Exchange.ManageV2 is the name the new Admin API pages print. Both are listed when the service principal publishes them.
$exchangeResourceAppId = '00000002-0000-0ff1-ce00-000000000000'
$exchangeScopeCandidates = @('Exchange.Manage', 'Exchange.ManageV2')

function Get-ExchangeSp {
    # $null when this tenant has no Office 365 Exchange Online service principal: normally a tenant with no Exchange Online.
    $f = [uri]::EscapeDataString("appId eq '$exchangeResourceAppId'")
    return (Invoke-Graph -Uri "https://graph.microsoft.com/v1.0/servicePrincipals?`$filter=$f&`$select=id,appId,displayName,oauth2PermissionScopes").value | Select-Object -First 1
}

function Get-ExchangeResourceAccess {
    # The requiredResourceAccess entry for Office 365 Exchange Online, or $null when the service principal is missing or publishes none of the names. $null means "leave it out", never "fail".
    # It takes everything it needs through parameters and reads no script variable, so the Pester suite can evaluate this function alone out of the file's syntax tree.
    param($Sp, [string[]]$ScopeNames)
    if (-not $Sp) { return $null }
    $scopes = @($Sp.oauth2PermissionScopes) | Where-Object { $ScopeNames -ccontains $_.value }
    if (-not @($scopes).Count) { return $null }
    return @{ resourceAppId = $Sp.appId; resourceAccess = @(@($scopes) | ForEach-Object { @{ id = $_.id; type = 'Scope' } }) }
}

# The Microsoft Teams Admin connector (2026-11-08). Skype and Teams Tenant Admin API is found by its application id, which Microsoft Learn prints on the Connect-MicrosoftTeams page
# (48ac35b8-9aa8-4d74-927d-1f4a14a0b239/.default). Its one delegated permission is user_impersonation; the id is read from the service principal, never typed. A tenant with no such service principal
# has nothing to list, and the script never creates it.
$teamsAdminResourceAppId = '48ac35b8-9aa8-4d74-927d-1f4a14a0b239'
$teamsAdminScopeCandidates = @('user_impersonation')

function Get-TeamsAdminSp {
    # $null when this tenant has no Skype and Teams Tenant Admin API service principal: normally a tenant that has never used Teams.
    $f = [uri]::EscapeDataString("appId eq '$teamsAdminResourceAppId'")
    return (Invoke-Graph -Uri "https://graph.microsoft.com/v1.0/servicePrincipals?`$filter=$f&`$select=id,appId,displayName,oauth2PermissionScopes").value | Select-Object -First 1
}

# The Microsoft Power Platform Admin connector (2026-11-08). TWO resources, because a v2.0 admin consent names one: the Power Platform API (8578e004-a5c6-46e7-913e-12f58912df43, licensing and billing
# policies, environment groups and management settings) and the Power Apps Service (475226c6-020e-4fb2-8a90-7a972cbfc1d4, the audience of the environments and data policy hosts). Both ids are printed on Microsoft Learn's Power Platform API pages.
# Every permission id is read from the service principal, never typed. A tenant with no such service principal has nothing to list, and the script never creates it.
$powerPlatformApiAppId = '8578e004-a5c6-46e7-913e-12f58912df43'
$powerPlatformApiScopeCandidates = @('EnvironmentManagement.Environments.Read', 'EnvironmentManagement.Groups.Read', 'EnvironmentManagement.Groups.ReadWrite', 'EnvironmentManagement.Settings.Read', 'EnvironmentManagement.Settings.ReadWrite', 'Licensing.Allocations.Read', 'Licensing.BillingPolicies.Read', 'Licensing.BillingPolicies.ReadWrite')
$powerAppsServiceAppId = '475226c6-020e-4fb2-8a90-7a972cbfc1d4'
$powerAppsServiceScopeCandidates = @('User')

function Get-PowerPlatformSp {
    # $null when this tenant has no service principal for the application: normally a tenant that has never used Power Platform.
    param([Parameter(Mandatory)][string]$AppId)
    $f = [uri]::EscapeDataString("appId eq '$AppId'")
    return (Invoke-Graph -Uri "https://graph.microsoft.com/v1.0/servicePrincipals?`$filter=$f&`$select=id,appId,displayName,oauth2PermissionScopes").value | Select-Object -First 1
}

function Get-PurviewSpByUrl {
    # The Microsoft Purview connector (2026-11-08). No source read for this build prints the application id of the Security and Compliance PowerShell service, so it is found by the resource URL it carries
    # (the Partner Center approach below). $null when the tenant has no service principal with that URL.
    param([string]$Url)
    $f = [uri]::EscapeDataString("servicePrincipalNames/any(n:n eq '$Url')")
    return (Invoke-Graph -Uri "https://graph.microsoft.com/v1.0/servicePrincipals?`$filter=$f&`$select=id,appId,displayName,oauth2PermissionScopes").value | Select-Object -First 1
}

function Resolve-ScopeIds {
    param($Sp, [string[]]$Names)
    $map = @{}; foreach ($s in $Sp.oauth2PermissionScopes) { $map[$s.value] = $s.id }
    $missing = @(); $access = @()
    foreach ($n in $Names) {
        if ($map.ContainsKey($n)) { $access += @{ id = $map[$n]; type = 'Scope' } }
        elseif ($n -notin @('openid', 'profile', 'email', 'offline_access')) { $missing += $n }
    }
    if ($missing.Count) { throw "UNRESOLVED on $($Sp.displayName): $($missing -join ', ')" }
    return $access
}

# The SharePoint Admin connector (2026-11-08) lists two Graph permissions beyond the tier rosters above (admin/sharepoint/settings) and AllSites.FullControl on Office 365 SharePoint Online
# (Learn: sharepoint-admin-apis-authentication-and-authorization). They are appended AFTER the tier is applied and kept out of the pinned arrays, which are held to the Microsoft Graph connector's own list.
# AllSites.FullControl has no narrower form, so the Read tier carries it too: the person's own SharePoint role is what limits what a call can do.
$sharePointGraphScopes = @('SharePointTenantSettings.ReadWrite.All', 'SharePointTenantSettings.Read.All')
$graphScopesRequested = if ($SkipSharePointAdmin) { @($graphScopes) } else { @($graphScopes) + $sharePointGraphScopes }

$rra = @(
    @{ resourceAppId = $graphSp.appId; resourceAccess = @(Resolve-ScopeIds $graphSp $graphScopesRequested) }
    @{ resourceAppId = $armSp.appId;   resourceAccess = @(Resolve-ScopeIds $armSp   @('user_impersonation')) }
)
if ($SkipSharePointAdmin) {
    Write-Host 'SharePoint Admin: not listed (-SkipSharePointAdmin).'
} else {
    $sharePointSp = Get-ResourceSp -WellKnownAppId '00000003-0000-0ff1-ce00-000000000000'   # Office 365 SharePoint Online
    $rra += @{ resourceAppId = $sharePointSp.appId; resourceAccess = @(Resolve-ScopeIds $sharePointSp @('AllSites.FullControl')) }
    Write-Host 'SharePoint Admin: listing AllSites.FullControl and the SharePoint tenant-settings permissions (needed only for the Microsoft SharePoint Admin connector).'
}

$partnerCenterAccess = $null
if ($SkipPartnerCenter) {
    Write-Host 'Partner Center: not listed (-SkipPartnerCenter).'
} else {
    $partnerCenterLookupFailed = $false
    try { $partnerCenterAccess = Get-PartnerCenterResourceAccess -Sp (Get-PartnerCenterSp) -ScopeName $partnerCenterScopeName }
    catch {
        $partnerCenterLookupFailed = $true
        Write-Warning "Could not look up the Microsoft Partner Center application, so its permission is not listed: $($_.Exception.Message)"
    }
    if ($partnerCenterAccess) {
        $rra += $partnerCenterAccess
        Write-Host "Partner Center: listing $partnerCenterScopeName (needed only for 'Authorize all customers' and the Partner Center billing tools)."
    } elseif ($partnerCenterLookupFailed) {
        Write-Host 'Partner Center: not listed because the lookup failed (see the warning above). Run the script again, or add the permission in the Microsoft Entra admin center. Nothing else is affected.'
    } else {
        Write-Host 'Partner Center: not listed. A tenant that is not a Cloud Solution Provider partner normally has no Microsoft Partner Center application. Nothing else is affected.'
    }
}

if ($SkipDefenderForEndpoint) {
    Write-Host 'Defender for Endpoint: not listed (-SkipDefenderForEndpoint).'
} else {
    $defenderAccess = $null
    $defenderLookupFailed = $false
    try { $defenderAccess = Get-DefenderResourceAccess -Sp (Get-DefenderSp) -ScopeNames $defenderScopeCandidates }
    catch {
        $defenderLookupFailed = $true
        Write-Warning "Could not look up the WindowsDefenderATP application, so its permissions are not listed: $($_.Exception.Message)"
    }
    if ($defenderAccess) {
        $rra += $defenderAccess
        Write-Host "Defender for Endpoint: listing $(@($defenderAccess.resourceAccess).Count) WindowsDefenderATP delegated permissions (needed only for the Microsoft Defender for Endpoint connector)."
    } elseif ($defenderLookupFailed) {
        Write-Host 'Defender for Endpoint: not listed because the lookup failed (see the warning above). Run the script again if you use that connector.'
    } else {
        Write-Host 'Defender for Endpoint: not listed. A tenant without Defender for Endpoint or Defender for Business normally has no WindowsDefenderATP application. Nothing else is affected.'
    }
}
if ($SkipExchangeOnline) {
    Write-Host 'Exchange Online: not listed (-SkipExchangeOnline).'
} else {
    $exchangeAccess = $null
    $exchangeLookupFailed = $false
    try { $exchangeAccess = Get-ExchangeResourceAccess -Sp (Get-ExchangeSp) -ScopeNames $exchangeScopeCandidates }
    catch {
        $exchangeLookupFailed = $true
        Write-Warning "Could not look up the Office 365 Exchange Online application, so its permission is not listed: $($_.Exception.Message)"
    }
    if ($exchangeAccess) {
        $rra += $exchangeAccess
        Write-Host "Exchange Online: listing $(@($exchangeAccess.resourceAccess).Count) Office 365 Exchange Online delegated permission(s) (needed only for the Microsoft Exchange Online connector)."
    } elseif ($exchangeLookupFailed) {
        Write-Host 'Exchange Online: not listed because the lookup failed (see the warning above). Run the script again if you use that connector.'
    } else {
        Write-Host 'Exchange Online: not listed. A tenant with no Exchange Online normally has no Office 365 Exchange Online application. Nothing else is affected.'
    }
}
if ($SkipTeamsAdmin) {
    Write-Host 'Teams Admin: not listed (-SkipTeamsAdmin).'
} else {
    $teamsAdminAccess = $null
    $teamsAdminLookupFailed = $false
    try { $teamsAdminAccess = Get-ExchangeResourceAccess -Sp (Get-TeamsAdminSp) -ScopeNames $teamsAdminScopeCandidates }
    catch {
        $teamsAdminLookupFailed = $true
        Write-Warning "Could not look up the Skype and Teams Tenant Admin API application, so its permission is not listed: $($_.Exception.Message)"
    }
    if ($teamsAdminAccess) {
        $rra += $teamsAdminAccess
        Write-Host "Teams Admin: listing $(@($teamsAdminAccess.resourceAccess).Count) Skype and Teams Tenant Admin API delegated permission(s) (needed only for the Microsoft Teams Admin connector)."
    } elseif ($teamsAdminLookupFailed) {
        Write-Host 'Teams Admin: not listed because the lookup failed (see the warning above). Run the script again if you use that connector.'
    } else {
        Write-Host 'Teams Admin: not listed. A tenant that has never used Teams normally has no Skype and Teams Tenant Admin API application. Nothing else is affected.'
    }
}
if ($SkipPowerPlatform) {
    Write-Host 'Power Platform: not listed (-SkipPowerPlatform).'
} else {
    foreach ($resource in @(
            @{ AppId = $powerPlatformApiAppId; Display = 'Power Platform API'; Candidates = $powerPlatformApiScopeCandidates },
            @{ AppId = $powerAppsServiceAppId; Display = 'Power Apps Service'; Candidates = $powerAppsServiceScopeCandidates })) {
        $powerPlatformAccess = $null
        $powerPlatformLookupFailed = $false
        try { $powerPlatformAccess = Get-ExchangeResourceAccess -Sp (Get-PowerPlatformSp -AppId $resource.AppId) -ScopeNames $resource.Candidates }
        catch {
            $powerPlatformLookupFailed = $true
            Write-Warning "Could not look up the Power Platform application $($resource.Display), so its permission is not listed: $($_.Exception.Message)"
        }
        if ($powerPlatformAccess) {
            $rra += $powerPlatformAccess
            Write-Host "Power Platform: listing $(@($powerPlatformAccess.resourceAccess).Count) $($resource.Display) delegated permission(s) (needed only for the Microsoft Power Platform Admin connector)."
        } elseif ($powerPlatformLookupFailed) {
            Write-Host "Power Platform: $($resource.Display) not listed because the lookup failed (see the warning above). Run the script again if you use that connector."
        } else {
            Write-Host "Power Platform: $($resource.Display) not listed. A tenant that has never used Power Platform normally has no such application, or it publishes none of the permissions. Nothing else is affected."
        }
    }
}
# The Microsoft Purview connector (2026-11-08): the cmdlet API and its content search session. NOTHING here fails the run; the result is a first-bug-report target (docs/architecture/connectors/Purview.md).
if ($SkipPurview) {
    Write-Host 'Microsoft Purview: not listed (-SkipPurview).'
} else {
    foreach ($purviewResource in @('https://ps.compliance.protection.outlook.com', 'https://dataservice.o365filtering.com')) {
        try {
            $purviewSp = Get-PurviewSpByUrl -Url $purviewResource
            if (-not $purviewSp) { Write-Host "Microsoft Purview: no application in this tenant carries $purviewResource, so nothing is listed for it."; continue }
            if (@($rra | Where-Object { $_.resourceAppId -eq $purviewSp.appId }).Count) { Write-Host "Microsoft Purview: $purviewResource is carried by $($purviewSp.displayName), which is already listed."; continue }
            $purviewAccess = Get-ExchangeResourceAccess -Sp $purviewSp -ScopeNames $exchangeScopeCandidates
            if ($purviewAccess) {
                $rra += $purviewAccess
                Write-Host "Microsoft Purview: listing $(@($purviewAccess.resourceAccess).Count) delegated permission(s) of $($purviewSp.displayName) ($purviewResource)."
            } else {
                Write-Host "Microsoft Purview: $($purviewSp.displayName) ($purviewResource) publishes none of $($exchangeScopeCandidates -join ', '). Left out."
            }
        }
        catch { Write-Warning "Could not look up $purviewResource, so nothing is listed for it: $($_.Exception.Message)" }
    }
}
$probe = @{ requiredResourceAccess = $rra } | ConvertTo-Json -Depth 10
if ($probe -notmatch '"resourceAccess":\s*\[') { throw 'Serialization sanity check failed - resourceAccess not an array.' }

function Merge-RedirectUris {
    # Append-only: every URL already on the app stays, in its order; each wanted URL that is not
    # there yet (compared case-insensitively) is added after them. Nothing is ever removed.
    #
    # This is what makes a SECOND run safe (Featurebase #228, 2026-09-18). The update path used to
    # PATCH web.redirectUris wholesale, so a customer who ran the script again with the other
    # region's -PortalHost lost the first region's URLs, and anyone whose app carried a
    # redirect URL of their own lost that too - with no error, because Graph accepts the smaller
    # list happily and the breakage only shows up at the next sign-in.
    #
    # It takes everything it needs through parameters and reads no script variable, so the parity
    # test can evaluate this function alone out of the file's syntax tree.
    param([string[]]$Existing, [string[]]$Wanted)
    $merged = [System.Collections.Generic.List[string]]::new()
    foreach ($uri in @($Existing) + @($Wanted)) {
        if ([string]::IsNullOrWhiteSpace($uri)) { continue }
        if (-not ($merged | Where-Object { $_ -ieq $uri })) { $merged.Add($uri) }
    }
    # The leading comma keeps the array whole across the caller's assignment: without it PowerShell
    # unrolls the result, and a one-element or empty merge would arrive as a bare string or $null.
    return , $merged.ToArray()
}

# The Defender for Endpoint callback is registered whether or not -SkipDefenderForEndpoint is set: a registered redirect URL grants nothing, and the sign-in
# StackJack starts for that connector asks for exactly /connector-callback/defenderendpoint (the connector's enum name, lower-cased), so an app
# without it answers a reply-address mismatch for every owner, member and agent enrollment (Astra F2, 2026-11-07). The Exchange Online callback (2026-11-08) is registered the same way, for the same reason.
# Append-only like the rest: the update path merges.
$redirectUris = @(
    "https://$PortalHost/connector-callback/msgraph"
    "https://$PortalHost/connector-callback/azure"
    "https://$PortalHost/connector-callback/defenderendpoint"
    "https://$PortalHost/connector-callback/exchangeonline"
    "https://$PortalHost/connector-callback/purview"
    "https://$PortalHost/connector-callback/sharepointadmin"
    "https://$PortalHost/connector-callback/teamsadmin"
    "https://$PortalHost/connector-callback/powerplatform"
    "https://$PortalHost/consent-complete"
)

$appBody = @{
    displayName            = $DisplayName
    signInAudience         = 'AzureADMultipleOrgs'   # multitenant: required for GDAP customer-tenant consent
    web                    = @{ redirectUris = $redirectUris }
    requiredResourceAccess = $rra
}

if ($AppId) {
    # Select `web` as well: the merge needs the app's CURRENT redirect URLs, and a PATCH that sent
    # only this run's URLs would silently drop every other one.
    $app = Invoke-Graph -Uri "https://graph.microsoft.com/v1.0/applications(appId='$AppId')?`$select=id,appId,displayName,web"
    $mergedRedirectUris = Merge-RedirectUris -Existing @($app.web.redirectUris) -Wanted $redirectUris
    $appBody.web = @{ redirectUris = @($mergedRedirectUris) }
    # Same sanity check as resourceAccess above, and it rejects BOTH ways this value can go wrong:
    # a single URL unwrapped to a bare string, and a nested array. The create path needs no probe -
    # its value is the literal built above.
    $webProbe = @{ web = $appBody.web } | ConvertTo-Json -Depth 10
    if ($webProbe -notmatch '"redirectUris":\s*\[\s*"') { throw 'Serialization sanity check failed - redirectUris not an array of URL strings.' }
    Invoke-Graph -Method PATCH -Uri "https://graph.microsoft.com/v1.0/applications/$($app.id)" -Body $appBody
    Write-Host "UPDATED existing app '$($app.displayName)' ($($app.appId)). It now carries $(@($mergedRedirectUris).Count) redirect URL(s); the ones already registered were kept."
} else {
    $app = Invoke-Graph -Method POST -Uri 'https://graph.microsoft.com/v1.0/applications' -Body $appBody
    Write-Host "CREATED app '$($app.displayName)' ($($app.appId))."
}

$secret = Invoke-Graph -Method POST -Uri "https://graph.microsoft.com/v1.0/applications/$($app.id)/addPassword" -Body @{
    passwordCredential = @{
        displayName = "StackJack connector secret ($PermissionTier tier)"
        endDateTime = (Get-Date).AddYears($SecretYears).ToUniversalTime().ToString('o')
    }
}

Write-Host ''
Write-Host '==== PASTE THESE INTO STACKJACK (Connectors -> Microsoft Graph / Azure -> Advanced) ===='
Write-Host "Application (client) ID : $($app.appId)"
Write-Host "Client secret           : $($secret.secretText)"
Write-Host "Secret expires          : $($secret.endDateTime)  (rotate in StackJack before then; users reconnect after a rotation)"
Write-Host ''
Write-Host "Pick the SAME permission tier ($($PermissionTier.ToLower())) in StackJack's dropdown so the consent prompt matches this registration."
Write-Host 'The secret above is shown ONCE. Store it in your password manager.'
if ($partnerCenterAccess) {
    Write-Host ''
    Write-Host "Partner Center: $partnerCenterScopeName is LISTED on the app, not yet approved. For 'Authorize all customers', an administrator in your tenant approves it once:"
    Write-Host '  Microsoft Entra admin center -> App registrations -> this app -> API permissions -> Grant admin consent.'
}

Authorize all customers from your own shell

The Authorize all customers button on the Microsoft Graph and Microsoft Azure connector cards records your app as consented in every customer tenant you manage through GDAP. grant-byo-microsoft-customer-consent.ps1 does the same run from your own shell or a runbook, for your own app only.

Before you run it:

  • PowerShell 7 with the Az.Accounts module, and Connect-AzAccount to your own tenant.

  • Your user is in the AdminAgents group in Partner Center, and in a GDAP security group that holds Application Administrator or Cloud Application Administrator for each customer.

  • Your app lists the Partner Center API permission user_impersonation (the provisioning script above lists it) and an administrator consented it once in your own tenant.

  • http://localhost:8400 is added to the app as a Web redirect URI (Entra, App registrations, Authentication).

Run it with -WhatIf first: it lists what it would send and sends nothing.

.\grant-byo-microsoft-customer-consent.ps1 -ClientId <your app id> -PartnerTenantId <your tenant id> -WhatIf

Save the block below as grant-byo-microsoft-customer-consent.ps1.

#Requires -Version 7.0
#Requires -Modules Az.Accounts
<#
.SYNOPSIS
    Records YOUR ORGANIZATION'S OWN Entra app registration (the one made by provision-byo-microsoft-appreg.ps1) as
    consented in every customer tenant you manage through GDAP, from your own shell ("authorize all customers").

.DESCRIPTION
    This is the command-line twin of the "Authorize all customers" button on StackJack's Connectors page, for partners who
    would rather run it from their own shell or a runbook. It calls Partner Center's application-consent API:

        POST https://api.partnercenter.microsoft.com/v1/customers/{customerId}/applicationconsents
        { "applicationId": "<your app>", "applicationGrants": [ { "enterpriseApplicationId": "<resource>", "scope": "A,B,C" } ] }

    ONLY FOR YOUR OWN APP. Partner Center records the consent for the application that signed the request, so this cannot
    consent StackJack's shared application, and the script takes no way to name one: the application is whichever
    registration -ClientId and -ClientSecret belong to. Run the provisioning script first.

    What it consents. The permissions are read off YOUR app registration (its requiredResourceAccess), resolved to names
    through each resource's published permission scopes, the procedure Microsoft documents. Only Microsoft Graph and Azure
    Service Management are consented; the OpenID Connect scopes (openid, profile, email, offline_access) are not sent.
    -Resource narrows the run to one of the two.

    Who it runs as. You sign in twice, as yourself, and nothing about either sign-in is stored:
      1. Connect-AzAccount (the same one the provisioning script uses) lets the script READ your app registration.
      2. A browser sign-in to YOUR app (the script prints the address and, if it can, opens it) gets a Partner Center token
         minted BY your app for your user. Microsoft requires that: the token's application must equal the
         applicationId in the request. When the browser ends on a page that cannot be reached (http://localhost...), copy the
         whole address from the address bar and paste it into the prompt. The secret never leaves this machine except in the
         token request to login.microsoftonline.com.

    What you need before running it:
      - Your user is a member of the AdminAgents group in Partner Center, and of a GDAP security group that holds
        Application Administrator or Cloud Application Administrator for each customer you want consented.
      - Your app registration lists the Partner Center API permission user_impersonation (delegated) and an administrator has
        consented it once in your own tenant. (StackJack's Connectors page prints that one-time link when it is missing.)
      - -RedirectUri (default http://localhost:8400) is registered on the app as a WEB redirect URI. The provisioning script
        registers only StackJack's three URLs, so add this one in Entra > App registrations > Authentication, once.

    Safe to repeat. Each customer is sent one request, with a fresh request id (Partner Center keeps a request id only across
    a retry of the same send, and nothing is retried); a customer consented earlier answers "already in place". A failure that would repeat for every remaining customer (a 401, a 429, three
    server faults in a row) stops the run; a refusal for one customer (no GDAP relationship, missing role, a service principal
    that does not exist in that tenant) is that customer's answer, printed with Microsoft's own reason, and the run goes on.
    Use -WhatIf to list what WOULD be sent without sending anything.

    After a run, StackJack may keep a customer's previous Microsoft token for up to an hour. If you run this script rather than
    the button, new permissions can take up to an hour to show up in StackJack for a customer that already had a token; the
    button clears that cache for you.

.PARAMETER ClientId
    Application (client) ID of YOUR app registration.

.PARAMETER ClientSecret
    A client secret of that app, as a SecureString. Prompted for when omitted.

.PARAMETER PartnerTenantId
    Your own tenant (GUID or verified domain), where your app is registered and your partner user lives.

.PARAMETER Resource
    Both (default), Graph or AzureManagement.

.PARAMETER CustomerTenantId
    Consent only these customers (tenant GUIDs). Default: every customer Partner Center lists for your account.

.PARAMETER RedirectUri
    The loopback redirect URI registered on the app. Default http://localhost:8400.

.PARAMETER MaxCustomers
    The most customers one run will attempt (default and ceiling 1000).
#>
[CmdletBinding(SupportsShouldProcess)]
param(
    [Parameter(Mandatory)][ValidatePattern('^[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$')][string]$ClientId,
    [SecureString]$ClientSecret,
    [Parameter(Mandatory)][ValidatePattern('^[A-Za-z0-9][A-Za-z0-9.-]*$')][string]$PartnerTenantId,
    [ValidateSet('Both', 'Graph', 'AzureManagement')][string]$Resource = 'Both',
    [ValidatePattern('^[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$')][string[]]$CustomerTenantId,
    [ValidatePattern('^http://localhost(:[0-9]{2,5})?(/.*)?$')][string]$RedirectUri = 'http://localhost:8400',
    [ValidateRange(1, 1000)][int]$MaxCustomers = 1000
)
$ErrorActionPreference = 'Stop'

$GraphAppId = '00000003-0000-0000-c000-000000000000'
$ArmAppId = '797f4846-ba00-4fd7-ba43-dac1f8f63013'
$PartnerCenterBase = 'https://api.partnercenter.microsoft.com/v1'
$PartnerCenterScope = 'https://api.partnercenter.microsoft.com/user_impersonation'
$Authority = 'https://login.microsoftonline.com'

# The four OpenID Connect scopes are not data permissions; consent for them is implied by any sign-in, and they are not sent.
$OpenIdScopes = @('openid', 'profile', 'email', 'offline_access')

# ---------------------------------------------------------------------------------------------------------------------
# Pure helpers. They take everything through parameters and read no script variable, so the Pester suite can evaluate each
# one alone out of this file's syntax tree (no dot-sourcing: dot-sourcing would run the whole flow against a live tenant).
# ---------------------------------------------------------------------------------------------------------------------

function ConvertTo-ConsentGrants {
    # requiredResourceAccess (the app registration) + the resources' permission names -> the applicationGrants array.
    # $ScopeNamesByResource maps resourceAppId -> hashtable(permissionId -> permission name).
    param(
        [Parameter(Mandatory)][AllowNull()]$RequiredResourceAccess,
        [Parameter(Mandatory)][hashtable]$ScopeNamesByResource,
        [Parameter(Mandatory)][ValidateSet('Both', 'Graph', 'AzureManagement')][string]$Resource,
        [string[]]$ExcludedScopes = @('openid', 'profile', 'email', 'offline_access')
    )
    $wanted = switch ($Resource) {
        'Graph'           { @('00000003-0000-0000-c000-000000000000') }
        'AzureManagement' { @('797f4846-ba00-4fd7-ba43-dac1f8f63013') }
        default           { @('00000003-0000-0000-c000-000000000000', '797f4846-ba00-4fd7-ba43-dac1f8f63013') }
    }
    $grants = [System.Collections.Generic.List[object]]::new()
    foreach ($resourceAppId in $wanted) {
        $ids = [System.Collections.Generic.List[string]]::new()
        foreach ($entry in @($RequiredResourceAccess)) {
            if ($null -eq $entry -or $entry.resourceAppId -ine $resourceAppId) { continue }
            foreach ($access in @($entry.resourceAccess)) {
                if ($access.type -ieq 'Scope') { $ids.Add([string]$access.id) }
            }
        }
        $names = $ScopeNamesByResource[$resourceAppId]
        if ($null -eq $names -or $ids.Count -eq 0) { continue }
        # Distinct and in ordinal order, so the same registration always produces the same request body.
        $set = [System.Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal)
        foreach ($id in $ids) {
            $name = $names[$id]
            if ($name -and ($ExcludedScopes -notcontains $name)) { [void]$set.Add([string]$name) }
        }
        if ($set.Count -eq 0) { continue }
        $resolved = [string[]]$set
        [Array]::Sort($resolved, [StringComparer]::Ordinal)
        # Comma-separated, as Microsoft's contract says.
        $grants.Add([pscustomobject]@{ enterpriseApplicationId = $resourceAppId; scope = ($resolved -join ',') })
    }
    return , $grants.ToArray()
}

function Get-CleanReason {
    # Microsoft's own reason out of an error body, flattened and bounded. Partner Center and Graph disagree about the
    # envelope (description / message / error.message), so each is tried; a body that is none of them is truncated, not dropped.
    param([AllowNull()][string]$Body, [int]$MaxLength = 300)
    if ([string]::IsNullOrWhiteSpace($Body)) { return '' }
    $reason = $null
    try {
        $json = $Body | ConvertFrom-Json -ErrorAction Stop
        if ($json -is [pscustomobject]) {
            $code = if ($json.code -is [string]) { $json.code } elseif ($json.errorCode -is [string]) { $json.errorCode } else { $null }
            $message = foreach ($name in 'description', 'message', 'error_description') {
                if ($json.$name -is [string] -and $json.$name.Trim()) { $json.$name; break }
            }
            if (-not $message -and $null -ne $json.error) {
                if ($json.error -is [string]) { $message = $json.error }
                else {
                    if (-not $code -and $json.error.code -is [string]) { $code = $json.error.code }
                    $message = foreach ($name in 'message', 'description') {
                        if ($json.error.$name -is [string] -and $json.error.$name.Trim()) { $json.error.$name; break }
                    }
                }
            }
            $reason = if ($code -and $message) { "${code}: $message" } elseif ($message) { $message } else { $code }
        }
    }
    catch { $reason = $null }
    if (-not $reason) { $reason = $Body }
    $flat = ($reason -replace '[\p{Cc}]', ' ').Trim()
    if ($flat.Length -le $MaxLength) { return $flat }
    return $flat.Substring(0, $MaxLength) + [char]0x2026
}

function ConvertTo-Base64Url {
    param([Parameter(Mandatory)][byte[]]$Bytes)
    return [Convert]::ToBase64String($Bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_')
}

function New-PkcePair {
    # RFC 7636 S256: a 43-character URL-safe verifier and its SHA-256 challenge.
    $random = [System.Security.Cryptography.RandomNumberGenerator]::GetBytes(32)
    $verifier = ConvertTo-Base64Url -Bytes $random
    $challenge = ConvertTo-Base64Url -Bytes ([System.Security.Cryptography.SHA256]::HashData([System.Text.Encoding]::ASCII.GetBytes($verifier)))
    return [pscustomobject]@{ Verifier = $verifier; Challenge = $challenge }
}

function ConvertFrom-JwtPayload {
    # The claims of a JWT, read without validating it. Used only to confirm the token was minted BY the app being consented.
    param([Parameter(Mandatory)][string]$Token)
    $parts = $Token.Split('.')
    if ($parts.Count -lt 2) { throw 'The access token is not a JWT.' }
    $payload = $parts[1].Replace('-', '+').Replace('_', '/')
    switch ($payload.Length % 4) { 2 { $payload += '==' } 3 { $payload += '=' } }
    return [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($payload)) | ConvertFrom-Json
}

function Get-ContinuationToken {
    # Partner Center surfaces the next page's token as body.continuationToken or as a header descriptor under links.next.headers.
    param([Parameter(Mandatory)]$Page)
    if ($Page.continuationToken -is [string] -and $Page.continuationToken) { return $Page.continuationToken }
    foreach ($header in @($Page.links.next.headers)) {
        $name = if ($header.key) { $header.key } else { $header.name }
        if ($name -ieq 'MS-ContinuationToken' -and $header.value) { return [string]$header.value }
    }
    return $null
}

# ---------------------------------------------------------------------------------------------------------------------
# The flow
# ---------------------------------------------------------------------------------------------------------------------

function Invoke-Graph {
    param([Parameter(Mandatory)][string]$Uri)
    $r = Invoke-AzRestMethod -Method GET -Uri $Uri
    if ($r.StatusCode -ge 300) { throw "Graph GET $Uri -> HTTP $($r.StatusCode): $(Get-CleanReason $r.Content)" }
    if ($r.Content) { return ($r.Content | ConvertFrom-Json) }
}

function Get-PartnerCenterToken {
    param([string]$Tenant, [string]$AppId, [SecureString]$Secret, [string]$Redirect)

    $pkce = New-PkcePair
    $state = [guid]::NewGuid().ToString('N')
    $query = @(
        "client_id=$([uri]::EscapeDataString($AppId))"
        'response_type=code'
        "redirect_uri=$([uri]::EscapeDataString($Redirect))"
        'response_mode=query'
        "scope=$([uri]::EscapeDataString("$PartnerCenterScope offline_access"))"
        "code_challenge=$($pkce.Challenge)"
        'code_challenge_method=S256'
        "state=$state"
        'prompt=select_account'
    ) -join '&'
    $url = "$Authority/$Tenant/oauth2/v2.0/authorize?$query"

    Write-Host ''
    Write-Host 'Sign in to YOUR app as the partner user who will record the consents (AdminAgents + GDAP application admin).'
    Write-Host $url
    try { Start-Process $url | Out-Null } catch { Write-Host '(Could not open a browser; open the address above yourself.)' }
    Write-Host ''
    Write-Host "After you sign in the browser lands on $Redirect, which shows an error page: that is expected. Copy the WHOLE address from the address bar."
    $pasted = Read-Host 'Paste it here'

    try { $uri = [uri]$pasted.Trim() } catch { throw 'That is not a web address.' }
    $returned = [System.Web.HttpUtility]::ParseQueryString($uri.Query)
    if ($returned['error']) { throw "Microsoft refused the sign-in: $($returned['error']) - $(Get-CleanReason $returned['error_description'])" }
    if ($returned['state'] -ne $state) { throw 'The address does not belong to this sign-in (the state differs). Run the script again.' }
    if (-not $returned['code']) { throw 'The address carries no authorization code.' }

    $plainSecret = [System.Net.NetworkCredential]::new('', $Secret).Password
    $body = @{
        client_id     = $AppId
        client_secret = $plainSecret
        grant_type    = 'authorization_code'
        code          = $returned['code']
        redirect_uri  = $Redirect
        code_verifier = $pkce.Verifier
        scope         = "$PartnerCenterScope offline_access"
    }
    $response = Invoke-WebRequest -Method Post -Uri "$Authority/$Tenant/oauth2/v2.0/token" -Body $body `
        -ContentType 'application/x-www-form-urlencoded' -SkipHttpErrorCheck
    if ($response.StatusCode -ge 300) {
        $reason = Get-CleanReason $response.Content
        if ($reason -match 'AADSTS65001|AADSTS650053') {
            throw "Partner Center is not consented for your app in your tenant yet. Add the Partner Center API permission user_impersonation (delegated) to the app registration and grant admin consent once. ($reason)"
        }
        throw "The token request was refused (HTTP $($response.StatusCode)): $reason"
    }
    $token = ($response.Content | ConvertFrom-Json).access_token
    $claims = ConvertFrom-JwtPayload -Token $token
    $mintedFor = if ($claims.appid) { $claims.appid } else { $claims.azp }
    if ($mintedFor -ine $AppId) { throw "The token was minted for application $mintedFor, not $AppId. Microsoft requires them to match." }
    return $token
}

function Send-PartnerCenter {
    param([string]$Method, [string]$Uri, [string]$Token, [string]$Body, [hashtable]$ExtraHeaders = @{})
    $headers = @{ Authorization = "Bearer $Token"; Accept = 'application/json' } + $ExtraHeaders
    $p = @{ Method = $Method; Uri = $Uri; Headers = $headers; SkipHttpErrorCheck = $true; TimeoutSec = 30 }
    if ($Body) { $p.Body = $Body; $p.ContentType = 'application/json' }
    try { return Invoke-WebRequest @p }
    catch { return [pscustomobject]@{ StatusCode = 0; Content = "Partner Center could not be reached ($($_.Exception.GetType().Name))."; Headers = @{} } }
}

# 1. The app registration -> the grants (read as YOU through Connect-AzAccount).
if (-not (Get-AzContext)) { Connect-AzAccount -Tenant $PartnerTenantId | Out-Null }
$filter = [uri]::EscapeDataString("appId eq '$ClientId'")
$app = (Invoke-Graph -Uri "https://graph.microsoft.com/v1.0/applications?`$filter=$filter&`$select=id,displayName,requiredResourceAccess").value | Select-Object -First 1
if (-not $app) { throw "No app registration with client ID $ClientId exists in the tenant you are signed in to. Sign in with an account from the tenant that owns the app." }

$scopeNames = @{}
foreach ($resourceAppId in @($GraphAppId, $ArmAppId)) {
    $f = [uri]::EscapeDataString("appId eq '$resourceAppId'")
    $sp = (Invoke-Graph -Uri "https://graph.microsoft.com/v1.0/servicePrincipals?`$filter=$f&`$select=appId,oauth2PermissionScopes").value | Select-Object -First 1
    $names = @{}
    foreach ($s in @($sp.oauth2PermissionScopes)) { if ($s.id -and $s.value) { $names[[string]$s.id] = [string]$s.value } }
    $scopeNames[$resourceAppId] = $names
}
$grants = ConvertTo-ConsentGrants -RequiredResourceAccess $app.requiredResourceAccess -ScopeNamesByResource $scopeNames -Resource $Resource
if (@($grants).Count -eq 0) { throw 'Your app registration requests no delegated permissions on the selected resource(s), so there is nothing to consent.' }

Write-Host "App: $($app.displayName) ($ClientId)"
foreach ($g in $grants) {
    $label = if ($g.enterpriseApplicationId -eq $GraphAppId) { 'Microsoft Graph' } else { 'Azure Service Management' }
    Write-Host ("  {0}: {1} permission(s)" -f $label, ($g.scope -split ',').Count)
}

$consentBody = [ordered]@{ applicationId = $ClientId; applicationGrants = @($grants) } | ConvertTo-Json -Depth 5 -Compress

# 2. The Partner Center token, minted by YOUR app for YOU.
if (-not $ClientSecret) { $ClientSecret = Read-Host -AsSecureString 'Client secret of your app registration' }
$partnerToken = Get-PartnerCenterToken -Tenant $PartnerTenantId -AppId $ClientId -Secret $ClientSecret -Redirect $RedirectUri

# 3. The customers.
$customers = [System.Collections.Generic.List[object]]::new()
if ($CustomerTenantId) {
    foreach ($id in ($CustomerTenantId | Select-Object -Unique)) { $customers.Add([pscustomobject]@{ id = $id; name = $id }) }
}
else {
    $continuation = $null
    for ($page = 0; $page -lt 50 -and $customers.Count -lt $MaxCustomers; $page++) {
        $extra = @{ 'ms-requestid' = [guid]::NewGuid().ToString() }
        if ($continuation) { $extra['MS-ContinuationToken'] = $continuation }
        $r = Send-PartnerCenter -Method GET -Uri "$PartnerCenterBase/customers?size=100" -Token $partnerToken -ExtraHeaders $extra
        if ($r.StatusCode -ge 300 -or $r.StatusCode -eq 0) {
            throw "Partner Center refused the customer list (HTTP $($r.StatusCode)). $(Get-CleanReason $r.Content) The user needs the Admin Agent role in Partner Center."
        }
        $data = $r.Content | ConvertFrom-Json
        foreach ($item in @($data.items)) {
            if (-not $item.id -or ($customers | Where-Object { $_.id -ieq $item.id })) { continue }
            if ($customers.Count -ge $MaxCustomers) { break }
            $name = if ($item.companyProfile.companyName) { $item.companyProfile.companyName } else { $item.id }
            $customers.Add([pscustomobject]@{ id = [string]$item.id; name = [string]$name })
        }
        $continuation = Get-ContinuationToken -Page $data
        if (-not $continuation) { break }
    }
}
Write-Host "$($customers.Count) customer(s) to authorize."

# 4. One attempt each. No retry.
$correlation = [guid]::NewGuid().ToString()
$results = [System.Collections.Generic.List[object]]::new()
$stopReason = $null
$consecutiveFaults = 0
foreach ($customer in $customers) {
    if ($stopReason) { $results.Add([pscustomobject]@{ Customer = $customer.name; CustomerId = $customer.id; Outcome = 'NotAttempted'; StatusCode = $null; Detail = '' }); continue }
    if ($customer.id -notmatch '^[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$') {
        $results.Add([pscustomobject]@{ Customer = $customer.name; CustomerId = $customer.id; Outcome = 'Refused'; StatusCode = $null; Detail = 'Not a tenant id; nothing was sent.' }); continue
    }
    if (-not $PSCmdlet.ShouldProcess("$($customer.name) ($($customer.id))", 'Record application consent')) {
        $results.Add([pscustomobject]@{ Customer = $customer.name; CustomerId = $customer.id; Outcome = 'NotAttempted'; StatusCode = $null; Detail = 'WhatIf' }); continue
    }

    $headers = @{
        'ms-correlationid' = $correlation
        # A FRESH id on every request. Partner Center keeps a request id only across a retry of the SAME send, and this script never
        # retries a send, so an id derived from the customer and the grants would only make a later run look like a duplicate.
        'ms-requestid'     = [guid]::NewGuid().ToString()
    }
    $r = Send-PartnerCenter -Method POST -Uri "$PartnerCenterBase/customers/$($customer.id)/applicationconsents" -Token $partnerToken -Body $consentBody -ExtraHeaders $headers
    $status = [int]$r.StatusCode
    $reason = Get-CleanReason $r.Content
    $fault = $false
    switch ($true) {
        ($status -eq 201) { $outcome = 'Created'; $detail = '' }
        ($status -eq 200) { $outcome = 'AlreadyInPlace'; $detail = 'Partner Center answered 200 OK rather than 201 Created: the request succeeded without recording a new consent.' }
        ($status -eq 409 -and $r.Content -match 'already') { $outcome = 'AlreadyInPlace'; $detail = $reason }
        ($status -eq 401) { $outcome = 'Refused'; $detail = 'Partner Center rejected the sign-in (401).'; $stopReason = 'Partner Center rejected the sign-in (401), which would repeat for every customer. The user must be in the AdminAgents group.' }
        ($status -eq 429) { $outcome = 'Refused'; $detail = 'Partner Center asked us to slow down (429).'; $stopReason = 'Partner Center is rate limiting this application (429); the run stopped instead of retrying. Run it again later.' }
        ($status -eq 0 -or $status -ge 500) { $outcome = 'Refused'; $detail = "Partner Center failed (HTTP $status). $reason".Trim(); $fault = $true }
        default { $outcome = 'Refused'; $detail = $reason }
    }
    $consecutiveFaults = if ($fault) { $consecutiveFaults + 1 } else { 0 }
    if (-not $stopReason -and $consecutiveFaults -ge 3) { $stopReason = 'Partner Center failed 3 times in a row, so the run stopped instead of retrying.' }
    $results.Add([pscustomobject]@{ Customer = $customer.name; CustomerId = $customer.id; Outcome = $outcome; StatusCode = $status; Detail = $detail })
}

$results | Format-Table Customer, CustomerId, Outcome, StatusCode, Detail -AutoSize -Wrap | Out-String | Write-Host
Write-Host ("Authorized: {0}  Already in place: {1}  Refused: {2}  Not attempted: {3}" -f
    @($results | Where-Object Outcome -eq 'Created').Count, @($results | Where-Object Outcome -eq 'AlreadyInPlace').Count,
    @($results | Where-Object Outcome -eq 'Refused').Count, @($results | Where-Object Outcome -eq 'NotAttempted').Count)
if ($stopReason) { Write-Warning $stopReason }
$results

Delegated permissions per tier

The script resolves each permission from your own tenant's Microsoft Graph service principal at run time, so it never prints the names. The lists below are what each tier requests, for building a matching permission set in a tool such as CIPP. The Azure connector requests one delegated scope, https://management.azure.com/user_impersonation, plus openid, profile, email and offline_access, on every tier.

You pick the tier again in StackJack when you connect. That choice sets what the Microsoft consent prompt asks for. It does not revoke permissions your organization already consented to, and it does not narrow a customer-tenant consent link, which grants whatever the application's own registration lists.

Full (78 scopes)

  • openid
  • profile
  • email
  • offline_access
  • User.Read
  • User.ReadWrite.All
  • Group.ReadWrite.All
  • Directory.ReadWrite.All
  • AdministrativeUnit.ReadWrite.All
  • AppRoleAssignment.ReadWrite.All
  • Directory.AccessAsUser.All
  • Device.Read.All
  • Application.ReadWrite.All
  • RoleManagement.ReadWrite.Directory
  • Policy.Read.All
  • Policy.ReadWrite.ConditionalAccess
  • Policy.ReadWrite.AuthenticationMethod
  • Policy.ReadWrite.MobilityManagement
  • AuditLog.Read.All
  • Reports.Read.All
  • Organization.ReadWrite.All
  • Domain.ReadWrite.All
  • IdentityRiskyUser.ReadWrite.All
  • IdentityRiskEvent.Read.All
  • Mail.ReadWrite
  • Mail.Send
  • Calendars.ReadWrite
  • Files.ReadWrite.All
  • Sites.ReadWrite.All
  • MailboxSettings.ReadWrite
  • Contacts.ReadWrite
  • Mail.ReadWrite.Shared
  • Calendars.ReadWrite.Shared
  • Contacts.ReadWrite.Shared
  • Mail.Send.Shared
  • Team.ReadBasic.All
  • Channel.ReadBasic.All
  • ChannelMessage.Read.All
  • TeamMember.ReadWrite.All
  • Team.Create
  • TeamSettings.ReadWrite.All
  • Channel.Create
  • ChannelSettings.ReadWrite.All
  • ChannelMessage.Send
  • Chat.ReadWrite
  • Presence.Read.All
  • SecurityEvents.ReadWrite.All
  • SecurityAlert.ReadWrite.All
  • SecurityIncident.ReadWrite.All
  • ThreatHunting.Read.All
  • RecordsManagement.ReadWrite.All
  • SensitivityLabel.Read
  • DeviceManagementManagedDevices.PrivilegedOperations.All
  • DeviceManagementManagedDevices.ReadWrite.All
  • DeviceManagementConfiguration.ReadWrite.All
  • DeviceManagementApps.ReadWrite.All
  • DeviceManagementServiceConfig.ReadWrite.All
  • DeviceManagementRBAC.Read.All
  • DeviceManagementRBAC.ReadWrite.All
  • DeviceManagementScripts.ReadWrite.All
  • DelegatedAdminRelationship.ReadWrite.All
  • UserAuthenticationMethod.ReadWrite.All
  • ManagedTenants.ReadWrite.All
  • CloudPC.ReadWrite.All
  • AuditLogsQuery.Read.All
  • ServiceHealth.Read.All
  • ServiceMessage.Read.All
  • ServiceMessageViewpoint.Write
  • eDiscovery.ReadWrite.All
  • Synchronization.ReadWrite.All
  • CopilotPolicySettings.ReadWrite
  • CopilotSettings-LimitedMode.ReadWrite
  • CopilotPackages.ReadWrite.All
  • CopilotCostManagement-Policy.ReadWrite.All
  • CopilotCostManagement-Assignment.ReadWrite.All
  • CopilotCostManagement-UserData.Read.All
  • CopilotCostManagement-CreditReq.ReadWrite.All
  • CopilotCostManagement.Read.All

Standard (72 scopes)

Everything except directory-privileged writes. The read-only forms of those areas are still requested, so listing delegated customers, domains, the organization and directory roles keeps working.

  • openid
  • profile
  • email
  • offline_access
  • User.Read
  • User.ReadWrite.All
  • Group.ReadWrite.All
  • Directory.ReadWrite.All
  • AdministrativeUnit.ReadWrite.All
  • Device.Read.All
  • Policy.Read.All
  • AuditLog.Read.All
  • Reports.Read.All
  • IdentityRiskEvent.Read.All
  • Mail.ReadWrite
  • Mail.Send
  • Calendars.ReadWrite
  • Files.ReadWrite.All
  • Sites.ReadWrite.All
  • MailboxSettings.ReadWrite
  • Contacts.ReadWrite
  • Mail.ReadWrite.Shared
  • Calendars.ReadWrite.Shared
  • Contacts.ReadWrite.Shared
  • Mail.Send.Shared
  • Team.ReadBasic.All
  • Channel.ReadBasic.All
  • ChannelMessage.Read.All
  • TeamMember.ReadWrite.All
  • Team.Create
  • TeamSettings.ReadWrite.All
  • Channel.Create
  • ChannelSettings.ReadWrite.All
  • ChannelMessage.Send
  • Chat.ReadWrite
  • Presence.Read.All
  • SecurityEvents.ReadWrite.All
  • SecurityAlert.ReadWrite.All
  • SecurityIncident.ReadWrite.All
  • ThreatHunting.Read.All
  • RecordsManagement.ReadWrite.All
  • SensitivityLabel.Read
  • DeviceManagementManagedDevices.ReadWrite.All
  • DeviceManagementConfiguration.ReadWrite.All
  • DeviceManagementApps.ReadWrite.All
  • DeviceManagementServiceConfig.ReadWrite.All
  • DeviceManagementRBAC.Read.All
  • DeviceManagementRBAC.ReadWrite.All
  • DeviceManagementScripts.ReadWrite.All
  • ManagedTenants.ReadWrite.All
  • CloudPC.ReadWrite.All
  • AuditLogsQuery.Read.All
  • ServiceHealth.Read.All
  • ServiceMessage.Read.All
  • ServiceMessageViewpoint.Write
  • eDiscovery.ReadWrite.All
  • Synchronization.ReadWrite.All
  • CopilotPolicySettings.ReadWrite
  • CopilotSettings-LimitedMode.ReadWrite
  • CopilotPackages.ReadWrite.All
  • CopilotCostManagement-Policy.ReadWrite.All
  • CopilotCostManagement-Assignment.ReadWrite.All
  • CopilotCostManagement-UserData.Read.All
  • CopilotCostManagement-CreditReq.ReadWrite.All
  • CopilotCostManagement.Read.All
  • RoleManagement.Read.Directory
  • Application.Read.All
  • UserAuthenticationMethod.Read.All
  • IdentityRiskyUser.Read.All
  • Domain.Read.All
  • Organization.Read.All
  • DelegatedAdminRelationship.Read.All

Read-only (64 scopes)

The read-only form of every capability the connector ships.

  • openid
  • profile
  • email
  • offline_access
  • User.Read
  • User.Read.All
  • Group.Read.All
  • Directory.Read.All
  • AdministrativeUnit.Read.All
  • Device.Read.All
  • Application.Read.All
  • RoleManagement.Read.Directory
  • Policy.Read.All
  • AuditLog.Read.All
  • Reports.Read.All
  • Organization.Read.All
  • Domain.Read.All
  • IdentityRiskyUser.Read.All
  • IdentityRiskEvent.Read.All
  • Mail.Read
  • Calendars.Read
  • Files.Read.All
  • Sites.Read.All
  • MailboxSettings.Read
  • Contacts.Read
  • Mail.Read.Shared
  • Calendars.Read.Shared
  • Contacts.Read.Shared
  • Team.ReadBasic.All
  • Channel.ReadBasic.All
  • ChannelMessage.Read.All
  • TeamMember.Read.All
  • TeamSettings.Read.All
  • ChannelSettings.Read.All
  • Chat.Read
  • Presence.Read.All
  • SecurityEvents.Read.All
  • SecurityAlert.Read.All
  • SecurityIncident.Read.All
  • ThreatHunting.Read.All
  • RecordsManagement.Read.All
  • SensitivityLabel.Read
  • DeviceManagementManagedDevices.Read.All
  • DeviceManagementConfiguration.Read.All
  • DeviceManagementApps.Read.All
  • DeviceManagementServiceConfig.Read.All
  • DeviceManagementRBAC.Read.All
  • DelegatedAdminRelationship.Read.All
  • UserAuthenticationMethod.Read.All
  • ManagedTenants.Read.All
  • CloudPC.Read.All
  • AuditLogsQuery.Read.All
  • ServiceHealth.Read.All
  • ServiceMessage.Read.All
  • eDiscovery.Read.All
  • Synchronization.Read.All
  • CopilotPolicySettings.Read
  • CopilotSettings-LimitedMode.Read
  • CopilotPackages.Read.All
  • CopilotCostManagement-Policy.Read.All
  • CopilotCostManagement-Assignment.Read.All
  • CopilotCostManagement-UserData.Read.All
  • CopilotCostManagement-CreditReq.Read.All
  • CopilotCostManagement.Read.All