Short answer: replace AdminAgents and DAP scripts with one multi-tenant app that each customer consents to, using least-privilege Microsoft Graph application permissions and a certificate kept in Azure Key Vault. Run the reporting from Azure Automation with a managed identity, so no admin password is stored anywhere.
Our unused licence report is the kind of script nobody thinks about until it breaks. In 2023 it had to be rewritten to use GDAP permissions. Our licence audit now runs unattended across customer tenants, and one recent pass flagged 107 items for a technician to review. Two tenants returned a Microsoft Graph 403 error and couldn’t be audited at all. That’s the lesson behind this guide: automation only sees the customers whose consent and access are actually in place.
Some of the most-used scripts on this knowledge base once relied on a single shortcut: register one app in your partner tenant, add it to the AdminAgents group, and it could quietly reach every customer you managed through delegated admin privileges (DAP). Later guides layered the Partner Center Secure Application Model on top, swapping a stored refresh token for MSOnline and AzureAD access tokens. If you built automation from those guides, it has stopped working, and that’s by design. This guide explains the GDAP secure application model as it stands today and the two patterns we use. For work a technician runs, we use delegated GDAP access through our open-source GDAP partner toolkit: a partner app with a certificate credential, a refresh token per technician in a SecretManagement vault, and Partner Center pre-consent. For unattended, read-only reporting, we use app-only consent with a certificate kept in Azure Key Vault. The guide ends with a complete script that collects Microsoft Secure Score and licence data from every consented customer.
Who this is for
- MSPs and Microsoft CSP partners who run scheduled PowerShell against many customer tenants (security posture, licensing, usage or alert reporting) and still have scripts based on AdminAgents, DAP or the Partner Center PowerShell module.
- Business owners and internal IT whose IT provider has asked them to approve an app in Microsoft 365. The consent step explains exactly what you are approving and how to remove it later.
What changed
The old approach broke for several separate reasons, so patching one of them won’t bring the scripts back:
- AdminAgents pre-consent only ever worked under DAP. Microsoft’s GDAP FAQ is explicit: “When DAP is active, they must add the app’s service principal to the Admin Agents SG in the partner tenant. With GDAP, partner must ensure their app is consented in customer tenant.” Microsoft also points out that pre-consented apps didn’t appear on the customer’s Enterprise applications page and that partners couldn’t review or audit those consents (Microsoft Learn).
- DAP is being replaced by granular delegated admin privileges (GDAP). GDAP gives least-privilege, time-bound access per customer. DAP has not been available with reseller relationships since 10 October 2023, customer tenants that partners create now get default GDAP roles instead of DAP, and Microsoft recommends moving every customer to GDAP as soon as possible (GDAP FAQ).
- The modules are gone. MSOnline was retired on 30 May 2025 (Microsoft Learn), and Microsoft announced that the AzureAD and AzureAD-Preview modules would be retired and stop working from mid-October 2025 (Microsoft Entra blog). Microsoft Graph PowerShell is the supported replacement.
- Azure AD Graph access has ended. Microsoft ended extended access to the Azure AD Graph API on 31 August 2025, and apps that still used it lost access from early September 2025, so scripts that requested tokens for
graph.windows.netmust move to Microsoft Graph (Microsoft Learn). - The Partner Center PowerShell module was never officially supported.
New-PartnerAccessTokencame from a community-maintained module whose documentation is now archived and no longer updated (Microsoft Learn). Our toolkit calls the Partner Center REST API directly instead. - Password-based workarounds are a dead end. Microsoft recommends a service principal with a managed identity, a federated credential or a certificate for unattended scripts instead of a stored user password (Microsoft Learn), and managed identities and service principals aren’t affected by Microsoft’s mandatory MFA enforcement (Microsoft Learn). Allow-listing office or Azure Function IP addresses to skip MFA is no longer needed and shouldn’t be used.
The older guides this replaces are How to connect to delegated Office 365 tenants using the secure app model and Create an Azure AD application with access to customer tenants. Don’t reuse the app registrations they created. Delete them: they typically hold long-lived client secrets that were exported to CSV files. The Clean up the old setup note near the end of this guide lists everything to remove.
Two ways to automate across customers, and how they differ
There are two ways to run code against a customer tenant today. They are not interchangeable, and the differences matter for security and for your agreement with the customer. Throughout this guide, boxes marked GDAP vs app-only call out where the two behave differently.
| GDAP delegated access (app + user, our toolkit) | App-only consent (the reporting script in this guide) | |
|---|---|---|
| Who is signed in | A named technician signs in once with MFA and the app acts as that technician. Microsoft’s model stores a refresh token for the signed-in account. Our toolkit keeps one per technician, so every action traces to a named person. | Nobody. The app signs in as itself with its certificate. |
| What limits access | The Microsoft Entra roles your GDAP security group holds in that customer, and the relationship’s end date. | Only the Microsoft Graph application permissions the customer consented to. GDAP roles and dates don’t apply. |
| How consent is given | Automatable through the Partner Center application consent API, when the GDAP relationship includes Application Administrator or Cloud Application Administrator. Our toolkit’s Grant-MspPartnerAppConsent makes that call and confirms each grant through Microsoft Graph. |
Manually, with the tenant-wide admin consent link, approved in the customer’s tenant by an admin who is allowed to consent to Microsoft Graph application permissions. |
| Secret to protect | Each technician’s refresh token (renewed at least every 90 days), kept in a SecretManagement vault, plus the app’s certificate. A refresh token can’t be used without the certificate’s private key. | The certificate’s private key. |
| When access ends | When the GDAP relationship expires or the roles are removed. | When the customer deletes the enterprise app or you remove the certificate. It isn’t tied to your GDAP end date. |
| Best suited to | Admin changes and write operations that should stay inside GDAP’s time-bound, role-based limits. | Scheduled, read-only reporting with tightly scoped permissions. |
GDAP vs app-only: what Microsoft says
Microsoft’s GDAP migration guidance says explicit application-only consent “isn’t compatible with the time-limited minimum-rights contract that GDAP manages”, so the Partner Center consent API only handles app + user consent (Microsoft Learn). The GDAP FAQ adds that an app using application-only permissions “must be manually consented to” with the tenant-wide admin consent URL (GDAP FAQ). In plain English: app-only access is a direct arrangement between the customer and your app, outside GDAP. That is why we keep it read-only, get the customer’s own administrator to approve it, and record that approval.
We use both. For anything a technician runs, including changes, investigations and Partner Center consent itself, we use delegated GDAP access through our toolkit, so every action runs as a named person inside their GDAP roles. For scheduled, read-only reporting with nobody at the keyboard, we use app-only consent, because it needs no standing user account and no refresh token, and the credential is a certificate rather than a password. The toolkit’s own 08 Unattended automation guide reaches the same conclusion.
Delegated access with our GDAP partner toolkit (tested)
MspGdap is a free PowerShell module (MIT licence) published on GitHub as our GDAP partner toolkit. It replaces New-PartnerAccessToken and the archived Partner Center PowerShell module with direct calls to the Microsoft identity platform and Partner Center REST APIs. It was tested live on 7 October 2026 against a Microsoft partner tenant and a GDAP customer: app creation, technician token registration, Partner Center pre-consent, Microsoft Graph, Exchange Online and Security and Compliance PowerShell with delegated GDAP tokens.
- Create one multi-tenant partner app in your partner tenant with
New-MspPartnerApp. It has delegated permissions only, a certificate credential and no client secret, and it can be limited to your technicians’ security group. The toolkit recommends a non-exportable certificate on each technician workstation (02 Create the partner app). - Register a refresh token per technician with
Register-MspPartnerToken. The technician signs in once in the browser with MFA (authorisation code flow with PKCE, never device code). The refresh token goes straight into a SecretManagement vault (SecretStore on the workstation, or Azure Key Vault) and is rewritten every time Microsoft rotates it. It’s useless without the partner app’s certificate (03 Register a technician token). - Pre-consent the app into each customer with
Grant-MspPartnerAppConsent. It calls the Partner Center application consent API one resource at a time and reads each grant back through Microsoft Graph.Test-MspPartnerAppConsentchecks it again later (04 Pre-consent customers). - Work in any customer with
Invoke-MspGraphRequestorConnect-MspGraphfor Microsoft Graph,Connect-MspExchangeOnlinefor Exchange Online andConnect-MspSecurityCompliancefor Security and Compliance PowerShell. Access tokens are cached in memory per customer and resource, andDisconnect-Mspclears them (06 Token caching and validation).
The short version, with your own values in place of the placeholders. Create the partner app first, as described in 02 Create the partner app.
# Once per workstation, from a clone of the repository (PowerShell 7.4 or later) Install-Module -Name Microsoft.PowerShell.SecretManagement, Microsoft.PowerShell.SecretStore -Repository PSGallery -Scope CurrentUser Register-SecretVault -Name 'MspGdap' -ModuleName 'Microsoft.PowerShell.SecretStore' Import-Module ./src/MspGdap/MspGdap.psd1 Set-MspConfiguration -PartnerTenantId '<PartnerTenantId>' -AppId '<PartnerAppId>' -CertificateThumbprint '<Thumbprint>' -VaultName 'MspGdap' # Once per technician (and again if the token is revoked or unused for 90 days) Register-MspPartnerToken -UserPrincipalName 'jane.admin@yourmsp.com.au' -SetAsDefault # Once per customer: pre-consent the partner app through Partner Center, then check it Grant-MspPartnerAppConsent -TenantId 'customer.onmicrosoft.com' -ManifestPath ./manifests/partner-app.minimal.json -WhatIf Grant-MspPartnerAppConsent -TenantId 'customer.onmicrosoft.com' -ManifestPath ./manifests/partner-app.minimal.json Test-MspPartnerAppConsent -TenantId 'customer.onmicrosoft.com' -ManifestPath ./manifests/partner-app.minimal.json # Every day: Microsoft Graph and Exchange Online in a customer tenant Invoke-MspGraphRequest -TenantId 'customer.onmicrosoft.com' -Method GET -Uri 'v1.0/organization' Connect-MspExchangeOnline -TenantId 'customer.onmicrosoft.com' Get-OrganizationConfig | Select-Object DisplayName Disconnect-Msp
The repository’s scripts folder has delegated versions of the reports in this guide, including get-secure-scores.ps1 and export-unused-licences.ps1, which run against one customer or, with AllCustomers, every active GDAP customer. Most of those scripts haven’t been run against a live tenant, so try each one on a single customer first. A delegated refresh token can also run unattended, as the old Secure Application Model did, but the token carries every GDAP role of that technician. The toolkit’s guide treats that as a judgement call and prefers app-only access for scheduled jobs wherever Microsoft supports it. 07 Migrating from DAP and MSOnline maps the old patterns to their replacements.
App-only reporting: prerequisites
The rest of this guide sets up the app-only pattern for scheduled reporting. Both of its scripts parse cleanly, and the report script was tested against mocked Microsoft Graph cmdlets. Unlike the toolkit, they haven’t been run against a live tenant yet, so run the setup script with -WhatIf first and test the report against one consented customer before you schedule it.
- A partner tenant with GDAP relationships to your customers. The script can read your GDAP customer list, or you can pass tenant IDs yourself.
- An Azure subscription in your partner tenant with:
- A dedicated Azure Key Vault that uses the Azure role-based access control permission model. Keep nothing else in it, because any identity that can read its secrets can read this certificate’s private key.
- An Azure Automation account with a system-assigned managed identity turned on and a PowerShell 7 runtime environment (PowerShell 7.6, or 7.4 until its support ends on 10 November 2026), which includes the Az modules as default packages. Note the managed identity’s Object (principal) ID from Account Settings > Identity.
- PowerShell 7 on a privileged access workstation with these modules from the PowerShell Gallery:
Az.Accounts,Az.KeyVault,Az.Resources,Microsoft.Graph.AuthenticationandMicrosoft.Graph.Applications. Install them for your account withInstall-Module -Name Az.Accounts, Az.KeyVault, Az.Resources, Microsoft.Graph.Authentication, Microsoft.Graph.Applications -Scope CurrentUser. Our Microsoft Graph PowerShell guide covers the Graph side in more detail. - Roles, activated just in time and only for the setup: Reader and Key Vault Certificates Officer on the vault, Application Developer or Cloud Application Administrator in the partner tenant, and (to grant the managed identity access) Privileged Role Administrator in the partner tenant plus Key Vault Data Access Administrator on the vault.
- A web page you control for the consent redirect, such as a simple “Thanks, approval received” page on your website. Microsoft requires the redirect address to exactly match one registered on the app.
- A customer administrator for each tenant who holds Global Administrator or Privileged Role Administrator and can approve the app.
Least-privilege permissions used
| Permission or role | Granted to | Used for |
|---|---|---|
SecurityEvents.Read.All |
Reporting app, in each customer tenant | Reading Microsoft Secure Score (least privileged for this API) |
LicenseAssignment.Read.All |
Reporting app, in each customer tenant | Reading purchased and assigned licences (least privileged for this API) |
DelegatedAdminRelationship.Read.All |
Automation managed identity, in your partner tenant only | Listing your GDAP customers (least privileged for this API) |
| Key Vault Secrets User (Azure role) | Automation managed identity, on the dedicated vault | Reading the certificate, including its private key, at run time (Microsoft Learn) |
Keeping the GDAP customer list permission on the managed identity, not on the multi-tenant app, means customers are never asked to consent to a partner-only permission. Avoid broad permissions such as Directory.Read.All when a narrower one covers the API you call.
Step 1: Prepare Key Vault and Azure Automation
- In the Azure portal, create a key vault for this automation only and choose Azure role-based access control as the permission model.
- Under the vault’s Certificates > Certificate Contacts, add a shared mailbox so expiry notices reach your team, not one person.
- Turn on diagnostic settings for the vault and send the audit logs to your Log Analytics workspace, so every read of the certificate is recorded.
- Open your Automation account, go to Account Settings > Identity, set System assigned to On, and copy the Object (principal) ID.
Step 2: Create the certificate and the multi-tenant app
Save the script below as New-MspReportingApp.ps1 and run it from your privileged access workstation. It creates a self-signed certificate inside Key Vault, registers the app with Multiple Entra ID tenants as the supported account type, uploads only the certificate’s public key, grants the managed identity its two partner-side permissions, and prints the consent link for customers. It never creates a client secret. Before it creates anything, it checks that the vault uses Azure role-based access control and that no certificate or app with the same name already exists, and it stops if either does. Run it with -WhatIf first: the pre-flight checks still run, then it tells you what it would create and stops. Run it again without -WhatIf to make the changes.
<#
.SYNOPSIS
One-time setup for app-only Microsoft Graph reporting across customer tenants.
.DESCRIPTION
1. Checks that nothing with the same name already exists, before it creates anything.
2. Creates a certificate in Azure Key Vault, so the private key is never saved on a workstation.
3. Registers a multi-tenant app in your partner tenant with read-only Microsoft Graph
application permissions and the certificate's public key. No client secret is created.
4. Optionally lets your Azure Automation account's managed identity read the certificate
and your GDAP customer list.
5. Prints the admin consent link to send to each customer.
Run it interactively from a privileged access workstation. Every sign-in uses MFA, and both
sign-ins are kept to this PowerShell window and signed out at the end.
Run it with -WhatIf first to check the pre-flight tests and see what it would create.
.NOTES
Roles needed (activate them just in time and let them expire afterwards):
- Reader and Key Vault Certificates Officer on the key vault
- Application Developer or Cloud Application Administrator in the partner tenant
- Only with -AutomationIdentityObjectId: Privileged Role Administrator in the partner tenant,
plus Key Vault Data Access Administrator on the key vault
#>
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory)]
[string] $PartnerTenantId,
[Parameter(Mandatory)]
[string] $KeyVaultName,
[Parameter(Mandatory)]
[string] $ConsentRedirectUri,
[string] $CertificateName = 'msp-graph-reporting',
[string] $AppDisplayName = 'MSP Graph Reporting (read-only)',
[ValidateRange(1, 12)]
[int] $CertificateValidityMonths = 6,
[string] $AutomationIdentityObjectId
)
$ErrorActionPreference = 'Stop'
$graphAppId = '00000003-0000-0000-c000-000000000000'
# Keep the Azure sign-in in this window only, so no privileged context is saved to your profile
Disable-AzContextAutosave -Scope Process | Out-Null
try {
#region 1. Sign in and run pre-flight checks (nothing is created in this region)
Connect-AzAccount -Tenant $PartnerTenantId | Out-Null
$vault = Get-AzKeyVault -VaultName $KeyVaultName
if (-not $vault) {
throw "Key vault '$KeyVaultName' was not found. Check the name and that your Azure context is on the right subscription."
}
if (-not $vault.EnableRbacAuthorization) {
throw "Key vault '$KeyVaultName' uses the legacy access policy model. Switch it to Azure role-based access control first."
}
if (Get-AzKeyVaultCertificate -VaultName $KeyVaultName -Name $CertificateName) {
throw "A certificate named '$CertificateName' already exists in '$KeyVaultName'. Use a different -CertificateName, or follow the rotation steps instead of re-running setup."
}
$graphScopes = @('Application.ReadWrite.All')
if ($AutomationIdentityObjectId) {
$graphScopes += 'AppRoleAssignment.ReadWrite.All'
}
Connect-MgGraph -TenantId $PartnerTenantId -Scopes $graphScopes -ContextScope Process -NoWelcome
if (Get-MgApplication -Filter "displayName eq '$AppDisplayName'") {
throw "An app named '$AppDisplayName' already exists. Delete it or choose another -AppDisplayName."
}
$graphServicePrincipal = Get-MgServicePrincipal -Filter "appId eq '$graphAppId'" -Property 'id', 'appRoles'
function Get-GraphAppRoleId {
param(
[Parameter(Mandatory)]
[string] $Permission
)
$role = $graphServicePrincipal.AppRoles | Where-Object {
$_.Value -eq $Permission -and $_.AllowedMemberTypes -contains 'Application'
}
if (-not $role) {
throw "Microsoft Graph application permission '$Permission' was not found."
}
return $role.Id
}
# Look up every permission now, so a problem stops the script before anything is created
$securityEventsRoleId = Get-GraphAppRoleId -Permission 'SecurityEvents.Read.All'
$licenceReadRoleId = Get-GraphAppRoleId -Permission 'LicenseAssignment.Read.All'
if ($AutomationIdentityObjectId) {
$gdapReadRoleId = Get-GraphAppRoleId -Permission 'DelegatedAdminRelationship.Read.All'
}
#endregion
$plannedChanges = "Create certificate '$CertificateName' in '$KeyVaultName' and register app '$AppDisplayName'"
if ($AutomationIdentityObjectId) {
$plannedChanges += " and grant managed identity $AutomationIdentityObjectId Key Vault Secrets User plus DelegatedAdminRelationship.Read.All"
}
if (-not $PSCmdlet.ShouldProcess("Partner tenant $PartnerTenantId", $plannedChanges)) {
return
}
#region 2. Create the certificate in Azure Key Vault
$policyParams = @{
SecretContentType = 'application/x-pkcs12'
SubjectName = "CN=$CertificateName"
IssuerName = 'Self'
KeyType = 'RSA'
KeySize = 2048
ValidityInMonths = $CertificateValidityMonths
EmailAtNumberOfDaysBeforeExpiry = 30
}
$policy = New-AzKeyVaultCertificatePolicy @policyParams
Add-AzKeyVaultCertificate -VaultName $KeyVaultName -Name $CertificateName -CertificatePolicy $policy | Out-Null
# Wait up to five minutes for Key Vault to finish
$deadline = (Get-Date).AddMinutes(5)
do {
Start-Sleep -Seconds 5
$operation = Get-AzKeyVaultCertificateOperation -VaultName $KeyVaultName -Name $CertificateName
if ($operation.Status -eq 'inProgress' -and (Get-Date) -gt $deadline) {
throw "Key Vault is still creating '$CertificateName' after five minutes. Check the certificate in the Azure portal before you run anything again."
}
} while ($operation.Status -eq 'inProgress')
if ($operation.Status -ne 'completed') {
throw "Key Vault could not create the certificate: $($operation.ErrorMessage)"
}
$kvCertificate = Get-AzKeyVaultCertificate -VaultName $KeyVaultName -Name $CertificateName
$expiry = $kvCertificate.Certificate.NotAfter.ToString('yyyy-MM-dd')
Write-Output "Certificate created. Thumbprint: $($kvCertificate.Thumbprint). Expires: $expiry"
#endregion
#region 3. Register the multi-tenant app (application permissions only)
# Read-only, least-privilege permissions for the two reports in this guide
$requiredResourceAccess = @(
@{
ResourceAppId = $graphAppId
ResourceAccess = @(
@{
Id = $securityEventsRoleId
Type = 'Role'
}
@{
Id = $licenceReadRoleId
Type = 'Role'
}
)
}
)
$keyCredential = @{
Type = 'AsymmetricX509Cert'
Usage = 'Verify'
Key = $kvCertificate.Certificate.RawData
DisplayName = "$CertificateName (expires $expiry)"
}
$newAppParams = @{
DisplayName = $AppDisplayName
SignInAudience = 'AzureADMultipleOrgs'
Web = @{ RedirectUris = @($ConsentRedirectUri) }
RequiredResourceAccess = $requiredResourceAccess
KeyCredentials = @($keyCredential)
Notes = 'Read-only app-only reporting across consented customer tenants. Certificate credential stored in Azure Key Vault.'
}
$application = New-MgApplication @newAppParams
Write-Output "App registered. Application (client) ID: $($application.AppId)"
#endregion
#region 4. Optional: access for the Azure Automation managed identity
if ($AutomationIdentityObjectId) {
# Lets the runbook read the certificate, including its private key, from this vault
New-AzRoleAssignment -ObjectId $AutomationIdentityObjectId -RoleDefinitionName 'Key Vault Secrets User' -Scope $vault.ResourceId | Out-Null
# Lets the runbook read your GDAP customer list in the partner tenant (no customer data)
$appRoleAssignment = @{
PrincipalId = $AutomationIdentityObjectId
ResourceId = $graphServicePrincipal.Id
AppRoleId = $gdapReadRoleId
}
New-MgServicePrincipalAppRoleAssignment -ServicePrincipalId $AutomationIdentityObjectId -BodyParameter $appRoleAssignment | Out-Null
Write-Output 'Managed identity granted Key Vault Secrets User and DelegatedAdminRelationship.Read.All.'
}
#endregion
#region 5. Admin consent link for each customer
$consentLink = 'https://login.microsoftonline.com/{0}/v2.0/adminconsent?client_id={1}&scope={2}&redirect_uri={3}&state={4}'
$graphDefaultScope = [uri]::EscapeDataString('https://graph.microsoft.com/.default')
$encodedRedirect = [uri]::EscapeDataString($ConsentRedirectUri)
Write-Output 'Send each customer this link after replacing CUSTOMER-TENANT-ID and CUSTOMER-REF:'
Write-Output ($consentLink -f 'CUSTOMER-TENANT-ID', $application.AppId, $graphDefaultScope, $encodedRedirect, 'CUSTOMER-REF')
#endregion
}
finally {
# Sign out of both services, even if something above failed
try { Disconnect-MgGraph | Out-Null } catch { Write-Verbose 'Microsoft Graph was not connected.' }
try { Disconnect-AzAccount | Out-Null } catch { Write-Verbose 'Azure was not connected.' }
}
Run it like this (replace the example values), first with -WhatIf on the end, then without:
.\New-MspReportingApp.ps1 -PartnerTenantId 'aaaabbbb-0000-cccc-1111-dddd2222eeee' -KeyVaultName 'kv-msp-graph-reporting' -ConsentRedirectUri 'https://www.example.com.au/app-approved/' -AutomationIdentityObjectId '11112222-bbbb-3333-cccc-4444dddd5555'
Then check the new app in the Microsoft Entra admin center under Entra ID > App registrations:
- API permissions should list only
SecurityEvents.Read.AllandLicenseAssignment.Read.Allas Application permissions. Don’t grant admin consent here. Your own tenant doesn’t need it. - Certificates & secrets should show one certificate and no client secrets.
- Authentication > App instance property lock should be enabled for all properties. Microsoft turns it on by default for new applications since June 2026, and it stops anyone adding credentials to your app’s service principal inside a customer’s tenant (Microsoft Learn).
- Owners should list at least two named administrators, so the app isn’t orphaned when someone leaves.
About the certificate: Microsoft recommends a certificate rather than a client secret, and a certificate from a well-known certificate authority (managed in Azure Key Vault) for production (Microsoft Learn). The script uses a Key Vault self-signed certificate to keep the walkthrough short. If your policy requires a CA-signed certificate, change the issuer in the certificate policy and keep the rest of the process the same. The key must be exportable, because Microsoft Graph PowerShell signs the sign-in request on the machine running the script.
A secretless alternative: make the app trust a user-assigned managed identity on the Automation account as a federated identity credential. Microsoft supports this for multitenant apps reaching other tenants, and there is no private key to protect (Microsoft Learn). Connect-MgGraph has no built-in switch for it, so you exchange the managed identity token for an app token yourself and pass the result to Connect-MgGraph -AccessToken. It’s more moving parts than this guide covers, but worth considering once the certificate version is running.
Step 3: Get consent in each customer tenant
Admin consent creates an enterprise application (service principal) for your app in the customer’s tenant and grants it the permissions listed on your app registration. The link printed by the setup script looks like this:
https://login.microsoftonline.com/{customer-tenant-id}/v2.0/adminconsent?client_id={app-id}&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default&redirect_uri={your-encoded-redirect}&state={customer-ref}
- Replace
{customer-tenant-id}with the customer’s tenant ID and{customer-ref}with your ticket or customer reference. Using/.defaultasks for every application permission on the app registration, which is how Microsoft’s admin consent endpoint requests app permissions (Microsoft Learn). - Send the link to the customer’s administrator with a short explanation: the app name, that it is read-only, the two permissions and what they show, how often it runs, and how to remove it.
- The administrator signs in, reviews the permissions and selects Accept. They are redirected to your page with
admin_consent=Truein the address. - Record the approval (who, when, which permissions) in your ticketing system. Don’t treat the tenant ID in the redirect as proof of consent: Microsoft warns that value can be spoofed. Confirm it by running the script against that tenant.
GDAP vs app-only: who can approve
For app + user consent through the Partner Center API, Microsoft lists Application Administrator or Cloud Application Administrator in your GDAP relationship as enough. App-only Microsoft Graph permissions are stricter: Cloud Application Administrator and Application Administrator can’t approve Microsoft Graph application permissions. A Privileged Role Administrator or Global Administrator in the customer’s tenant must (Microsoft Learn). We ask the customer’s own administrator to approve it rather than holding that level of access ourselves.
Customers can see the app at any time in the Microsoft Entra admin center under Entra ID > Enterprise apps, review its permissions under Security > Permissions, and remove it by deleting the enterprise application (Microsoft Learn). That visibility is the main improvement over AdminAgents pre-consent.
Step 4: Deploy the reporting runbook
Save the script below as Get-CustomerGraphReport.ps1. It signs in to each customer tenant separately with Connect-MgGraph -TenantId -ClientId and the certificate, confirms the session is app-only, reads the latest Secure Score and the tenant’s licences, then disconnects before moving to the next tenant. A failure in one tenant is logged and the run carries on.
<#
.SYNOPSIS
Collects Microsoft Secure Score and licence data from every customer tenant that has
consented to your multi-tenant reporting app, using app-only certificate sign-in.
.DESCRIPTION
Built to run as an Azure Automation runbook (PowerShell 7 runtime) with a system-assigned
managed identity. The managed identity reads the certificate from Azure Key Vault and,
unless you pass -CustomerTenantId, reads your GDAP customer list from the partner tenant.
The script then gets a separate app-only Microsoft Graph token for each customer tenant.
For a local test, put a test certificate in Cert:\CurrentUser\My, pass
-CertificateThumbprint and list the tenants with -CustomerTenantId.
No secrets, tokens or private keys are written to the output or the log.
.EXAMPLE
.\Get-CustomerGraphReport.ps1 -ClientId '00001111-aaaa-2222-bbbb-3333cccc4444' -KeyVaultName 'kv-msp-automation' -CertificateName 'msp-graph-reporting'
.EXAMPLE
.\Get-CustomerGraphReport.ps1 -ClientId '00001111-aaaa-2222-bbbb-3333cccc4444' -CertificateThumbprint '<thumbprint>' -CustomerTenantId 'aaaabbbb-0000-cccc-1111-dddd2222eeee' -Report SecureScore
#>
[CmdletBinding(DefaultParameterSetName = 'KeyVault')]
param(
[Parameter(Mandatory)]
[string] $ClientId,
[Parameter(Mandatory, ParameterSetName = 'KeyVault')]
[string] $KeyVaultName,
[Parameter(Mandatory, ParameterSetName = 'KeyVault')]
[string] $CertificateName,
[Parameter(Mandatory, ParameterSetName = 'LocalCertificate')]
[string] $CertificateThumbprint,
[string[]] $CustomerTenantId,
[ValidateSet('SecureScore', 'Licences', 'Both')]
[string] $Report = 'Both',
[string] $OutputFolder = (Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath 'msp-graph-reports')
)
$ErrorActionPreference = 'Stop'
Import-Module Microsoft.Graph.Authentication, Microsoft.Graph.Security, Microsoft.Graph.Identity.DirectoryManagement
$runId = [guid]::NewGuid().ToString()
$runStamp = (Get-Date).ToUniversalTime().ToString('yyyyMMdd-HHmmss')
$null = New-Item -Path $OutputFolder -ItemType Directory -Force
$runLog = [System.Collections.Generic.List[object]]::new()
$secureScores = [System.Collections.Generic.List[object]]::new()
$licenceRows = [System.Collections.Generic.List[object]]::new()
function Add-RunLog {
param(
[string] $TenantId,
[string] $TenantName,
[string] $Status,
[string] $Detail
)
$entry = [pscustomobject]@{
TimestampUtc = (Get-Date).ToUniversalTime().ToString('o')
RunId = $runId
TenantId = $TenantId
TenantName = $TenantName
Status = $Status
Detail = $Detail
}
$runLog.Add($entry)
Write-Output ('{0} | {1} | {2} | {3} | {4}' -f $entry.TimestampUtc, $Status, $TenantName, $TenantId, $Detail)
}
#region Load the certificate
$certificate = $null
if ($PSCmdlet.ParameterSetName -eq 'KeyVault') {
Disable-AzContextAutosave -Scope Process | Out-Null
Connect-AzAccount -Identity | Out-Null
# A Key Vault certificate's secret holds the PFX, including the private key, as Base64
$pfxBytes = [System.Convert]::FromBase64String((Get-AzKeyVaultSecret -VaultName $KeyVaultName -Name $CertificateName -AsPlainText))
$certificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($pfxBytes, [string]::Empty)
[System.Array]::Clear($pfxBytes, 0, $pfxBytes.Length)
$certificateExpiry = $certificate.NotAfter
}
else {
$localCertificate = Get-Item -Path "Cert:\CurrentUser\My\$CertificateThumbprint"
$certificateExpiry = $localCertificate.NotAfter
}
Add-RunLog -TenantId '' -TenantName 'partner' -Status 'Info' -Detail "Certificate expires $($certificateExpiry.ToString('yyyy-MM-dd'))"
if ($certificateExpiry -lt (Get-Date).AddDays(30)) {
Write-Warning "The app certificate expires on $($certificateExpiry.ToString('yyyy-MM-dd')). Rotate it now."
}
#endregion
#region Build the customer list
if ($CustomerTenantId) {
$customers = foreach ($id in $CustomerTenantId) {
[pscustomobject]@{
TenantId = $id
DisplayName = $id
}
}
}
elseif ($PSCmdlet.ParameterSetName -eq 'KeyVault') {
# Partner tenant only: the managed identity needs DelegatedAdminRelationship.Read.All
Import-Module Microsoft.Graph.Identity.Partner
Connect-MgGraph -Identity -ContextScope Process -NoWelcome
$customers = Get-MgTenantRelationshipDelegatedAdminCustomer -All | Select-Object -Property TenantId, DisplayName
Disconnect-MgGraph | Out-Null
}
else {
throw 'When testing with -CertificateThumbprint, list the tenants to test with -CustomerTenantId.'
}
Add-RunLog -TenantId '' -TenantName 'partner' -Status 'Info' -Detail "Customer tenants to process: $(@($customers).Count)"
#endregion
#region Collect data from each customer tenant
foreach ($customer in $customers) {
try {
$connectParams = @{
TenantId = $customer.TenantId
ClientId = $ClientId
ContextScope = 'Process'
NoWelcome = $true
}
if ($certificate) {
$connectParams.Certificate = $certificate
}
else {
$connectParams.CertificateThumbprint = $CertificateThumbprint
}
# App-only token for this customer tenant only
Connect-MgGraph @connectParams
if ((Get-MgContext).AuthType -ne 'AppOnly') {
throw 'Expected an app-only Microsoft Graph session.'
}
if ($Report -in @('SecureScore', 'Both')) {
$score = Get-MgSecuritySecureScore -Top 1 | Select-Object -First 1
if ($score) {
$percent = $null
if ($score.MaxScore -gt 0) {
$percent = [math]::Round(($score.CurrentScore / $score.MaxScore) * 100, 1)
}
$secureScores.Add([pscustomobject]@{
TenantName = $customer.DisplayName
TenantId = $customer.TenantId
ScoreDate = $score.CreatedDateTime
CurrentScore = $score.CurrentScore
MaxScore = $score.MaxScore
Percent = $percent
LicensedUserCount = $score.LicensedUserCount
ActiveUserCount = $score.ActiveUserCount
})
}
}
if ($Report -in @('Licences', 'Both')) {
foreach ($sku in (Get-MgSubscribedSku -All)) {
$licenceRows.Add([pscustomobject]@{
TenantName = $customer.DisplayName
TenantId = $customer.TenantId
SkuPartNumber = $sku.SkuPartNumber
SkuId = $sku.SkuId
CapabilityStatus = $sku.CapabilityStatus
Purchased = $sku.PrepaidUnits.Enabled
Assigned = $sku.ConsumedUnits
Available = $sku.PrepaidUnits.Enabled - $sku.ConsumedUnits
Suspended = $sku.PrepaidUnits.Suspended
Warning = $sku.PrepaidUnits.Warning
})
}
}
Add-RunLog -TenantId $customer.TenantId -TenantName $customer.DisplayName -Status 'Success' -Detail ''
}
catch {
Add-RunLog -TenantId $customer.TenantId -TenantName $customer.DisplayName -Status 'Failed' -Detail $_.Exception.Message
}
finally {
if (Get-MgContext) {
Disconnect-MgGraph | Out-Null
}
}
}
#endregion
#region Save the results
if ($secureScores.Count -gt 0) {
$secureScores | Export-Csv -Path (Join-Path -Path $OutputFolder -ChildPath "secure-scores-$runStamp.csv") -NoTypeInformation
}
if ($licenceRows.Count -gt 0) {
$licenceRows | Export-Csv -Path (Join-Path -Path $OutputFolder -ChildPath "licences-$runStamp.csv") -NoTypeInformation
}
$runLog | Export-Csv -Path (Join-Path -Path $OutputFolder -ChildPath "run-log-$runStamp.csv") -NoTypeInformation
if ($certificate) {
$certificate.Dispose()
}
$failed = @($runLog | Where-Object -Property Status -EQ 'Failed')
Write-Output "Run $runId finished. Tenants: $(@($customers).Count). Failed: $($failed.Count). Output folder: $OutputFolder"
if ($failed.Count -gt 0) {
Write-Warning "$($failed.Count) tenant(s) failed. See run-log-$runStamp.csv for the reason."
}
#endregion
How to run it
In Azure Automation (recommended)
- In your Automation account, create a runtime environment with PowerShell and runtime version 7.6 (7.4 is supported only until 10 November 2026). Az modules are included.
- Add these modules to the runtime environment from the gallery, all at the same version:
Microsoft.Graph.Authentication,Microsoft.Graph.Security,Microsoft.Graph.Identity.DirectoryManagementandMicrosoft.Graph.Identity.Partner. - Create a PowerShell runbook that uses that runtime environment, paste in the script, then Save and Publish.
- Start a test run with ClientId, KeyVaultName, CertificateName and one consented tenant in CustomerTenantId. Check the job output for a Success line.
- Run it again without CustomerTenantId so it reads your GDAP customer list, then link it to a weekly schedule.
Files written to the sandbox’s temporary folder are discarded when the job ends. For production, add a final step that sends the CSV files somewhere permanent, such as an Azure Storage container that the same managed identity can write to, or pass the objects to your reporting tool. Secure Score data is a map of each customer’s weak points, so use a private container, give the managed identity Storage Blob Data Contributor on that container only, turn off shared key access on the storage account and don’t hand out SAS links.
On a workstation, for testing
Put a separate test certificate (with its private key) in Cert:\CurrentUser\My, one of the two stores Connect-MgGraph -CertificateThumbprint checks (Microsoft Learn), upload its public key to the app registration, then run:
.\Get-CustomerGraphReport.ps1 -ClientId '00001111-aaaa-2222-bbbb-3333cccc4444' -CertificateThumbprint '<test-certificate-thumbprint>' -CustomerTenantId 'aaaabbbb-0000-cccc-1111-dddd2222eeee' -Report Both -OutputFolder "$env:USERPROFILE\Reports\Graph"
Remove the test certificate from the app registration when you’re done, so only the Key Vault certificate remains.
Logging and monitoring
- Run log: every run writes
run-log-<timestamp>.csvwith the run ID, tenant, status and error message, and the same lines appear in the Automation job output. Tokens, private keys and secret values are never logged. - Customer side: each certificate sign-in appears in the customer’s Microsoft Entra service principal sign-in logs, so customers can see exactly when your app accessed their tenant (Microsoft Learn).
- Key Vault: with diagnostic logging on, every read of the certificate’s secret is recorded against the identity that read it (Microsoft Learn). Alert on reads by anything other than the Automation account’s managed identity.
- Failures: set an alert on failed or suspended Automation jobs, and review the run log weekly for tenants that keep failing. That usually means a customer removed the app or a new customer hasn’t approved it yet.
Rotating the certificate
Microsoft Entra ID only trusts public keys that are uploaded to the app registration, so every new certificate version has to be added there before the old one expires. The app can hold both at once, which makes rotation a no-downtime job:
- About 30 days before expiry (the vault emails your certificate contacts), open the certificate in Key Vault and select New Version. Key Vault can also renew self-signed certificates automatically (Microsoft Learn), but you still need the next step.
- Download the new version in CER format and upload it to the app registration under Certificates & secrets > Certificates.
- Let the runbook run. It always reads the current version of the secret, so it picks up the new certificate automatically.
- After a clean run, delete the old certificate from the app registration and disable the old version in Key Vault.
Customers don’t need to approve anything again, because the credential lives on your app registration, not in their tenant. Keep certificate lifetimes short (the setup script allows 12 months at most and defaults to 6).
Offboarding a customer
GDAP vs app-only: ending access
Ending or letting a GDAP relationship expire removes your technicians’ delegated access, but it doesn’t remove an app the customer consented to. When a customer leaves, ask their administrator to delete your enterprise application (or do it with them on the exit call), confirm it is gone, and remove the tenant from any list you pass to the script.
Troubleshooting
- AADSTS700016 (application not found in the directory): the customer hasn’t approved the app yet, removed it, or you used the wrong tenant ID. Send the consent link again.
- AADSTS700027 (client assertion failed signature validation): the certificate the script used isn’t on the app registration. This is common straight after a rotation where the new version wasn’t uploaded, or when a local test certificate was removed.
- AADSTS90002 (tenant not found): the tenant ID is wrong. Copy it from your GDAP customer list or the customer’s Microsoft Entra overview page.
- 403 Forbidden from Get-MgSecuritySecureScore or Get-MgSubscribedSku: the customer approved an older version of the app that didn’t include that permission. Admin consent covers the permissions listed at the time, so send the consent link again after adding a permission.
- Forbidden from Get-AzKeyVaultSecret: the managed identity is missing Key Vault Secrets User on the vault, or the vault still uses the legacy access policy model.
- Forbidden from Get-MgTenantRelationshipDelegatedAdminCustomer: the managed identity doesn’t have
DelegatedAdminRelationship.Read.Allin your partner tenant. Connect withConnect-MgGraph -Scopes 'Application.Read.All', 'AppRoleAssignment.ReadWrite.All' -ContextScope Processand run theGet-MgServicePrincipalandNew-MgServicePrincipalAppRoleAssignmentlines from regions 1 and 4 of the setup script on their own, then disconnect. Don’t re-run the whole script for this. Its duplicate guard will stop it anyway. - The customer’s administrator can’t approve the app: they probably hold Cloud Application Administrator or Application Administrator, which can’t consent to Microsoft Graph application permissions. A Global Administrator or Privileged Role Administrator needs to approve it.
- The consent page redirects to an error: the
redirect_uriin the link must exactly match the one registered on the app, including the trailing slash. - Connect-MgGraph can’t find the certificate locally:
-CertificateThumbprintloads the certificate fromCert:\CurrentUser\MyorCert:\LocalMachine\My. Check that the certificate, with its private key, is in one of those stores and that the account running the script can read the private key (Microsoft Learn). - The runbook fails while loading the certificate from Key Vault (for example “Keyset does not exist”): the sandbox may not be able to store the private key with the default settings. Pass
[System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::EphemeralKeySetas a third argument toX509Certificate2::new, so the key is held in memory only, and test again. - The setup script stops with “already exists”: that’s the duplicate guard working. Re-running setup would create a second app and a second certificate. If a previous run failed half-way, delete the partial app registration or certificate first, then run it again.
Important notes
- App-only access is tenant-wide. A Microsoft Graph application permission applies to the whole customer tenant, with no GDAP role or time limit around it. Only add read permissions to this app. Never add mailbox or file write permissions to a multi-tenant app that every customer has approved. For tasks such as removing a phishing email from mailboxes, use the customer’s Microsoft Defender or Microsoft Purview tools through GDAP instead.
- Use separate apps for separate jobs. If a new report needs a different permission, consider a second app rather than widening this one, so each customer approves only what they actually use.
- Clean up the old setup. Delete the old app registrations, not just their secrets (many old scripts created 99-year secrets). Remove any app service principals you added to your partner tenant’s AdminAgents group. Where the old scripts created the app in customer tenants (for example with the Partner Center consent cmdlets), those enterprise applications and their permissions stay in place until someone removes them, so remove them with each customer. Disable the dedicated user account the old model used for refresh tokens, revoke its sessions with
Revoke-MgUserSignInSession, remove it from AdminAgents, and delete every stored refresh token, secret and CSV file. - SharePoint scripts: if an old script used
Sites.Manage.AllorSites.FullControl.All, look atSites.Selected, which limits an app to the specific sites you grant (Microsoft Learn). - Secure Score dates: the report includes the date of the score it read. If a tenant’s score looks stale, check the ScoreDate column before drawing conclusions.
- AzureAD module status: Microsoft announced the AzureAD retirement from mid-October 2025. Treat any script that still calls
Connect-AzureADas broken and rewrite it with Microsoft Graph PowerShell.
Related resources
Microsoft Learn
- Migrate your CPV/CSP applications to use granular delegated admin privileges
- GDAP frequently asked questions
- Enable the secure application model
- Partner Center APIs for customer consent
- Grant tenant-wide admin consent to an application
- Microsoft identity platform admin consent protocols
- Use app-only authentication with the Microsoft Graph PowerShell SDK
- Connect-MgGraph reference
- About Azure Key Vault certificates
- Use a system-assigned managed identity for an Azure Automation account
- Configure app instance property lock
GCIT GDAP partner toolkit (GitHub)
- MspGdap: GDAP partner toolkit for Microsoft partners (README, threat model and quick start)
- 02 Create the partner app, 03 Register a technician token and 04 Pre-consent customers
- 06 Token caching and validation (includes common pitfalls in older Secure Application Model scripts)
- 08 Unattended automation
Related GCIT articles
- Export customers’ Microsoft Secure Scores to CSV and HTML reports
- How to detect a breach in Microsoft 365
- Run Exchange Online PowerShell across customer tenants with GDAP
- How to install Microsoft Graph PowerShell
Need help moving your automation to GDAP?
GCIT builds secure, least-privilege Microsoft 365 automation for Australian businesses, with no stored admin passwords and full visibility for customers. If you are still running DAP-era scripts, we can help you retire them safely.