Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darrenjrobinson/151e39fba6255447e04a41e24f280ef6 to your computer and use it in GitHub Desktop.
Save darrenjrobinson/151e39fba6255447e04a41e24f280ef6 to your computer and use it in GitHub Desktop.
Query Azure Service Management with an Azure AD Member Account to report on tenants the AAD User is federated to as a B2B Guest User. Associated blogpost https://blog.darrenjrobinson.com/azure-ad-user-account-federation-report
Import-Module MSAL.PS
Import-Module AzureADTenantID
# Use the Azure PowerShell Well-Known Client ID
$clientID = "1950a258-227b-4e31-a9cf-717495945fc2"
# Get UserUPN
$userUPN = Read-Host -Prompt "Please enter Azure AD User UPN"
$tenantName = $userUPN.Split("@")[1]
$tenantID = Get-AzureADTenantId -domain $tenantName
$scopes = "https://management.azure.com/user_impersonation"
# Interactive Flow
$clientApplication = Get-MsalClientApplication -ClientId $clientID -Authority "https://login.microsoftonline.com/$($tenantID)/" -ErrorAction SilentlyContinue
$msalCacheObj = $null
$msalCacheObj = $clientApplication | Get-MsalAccount -Username $userUPN -ErrorAction SilentlyContinue
if ($msalCacheObj) {
if ($msalCacheObj.Username -eq $userUPN) {
# new login for tokens
$myAccessToken = Get-MsalToken -ClientId $clientID -silent -TenantId $tenantId -Scopes $scopes -LoginHint $userUPN -RedirectUri "http://localhost" -Authority "https://login.microsoftonline.com/$($tenantID)/" -ForceRefresh
}
}
else {
# new login for tokens
$myAccessToken = Get-MsalToken -Interactive -ClientId $clientID -TenantId $tenantID -LoginHint $userUPN -Scopes $scopes -RedirectUri "http://localhost" -Authority "https://login.microsoftonline.com/$($tenantID)/"
}
$myFederatedTenants = $null
$myFederatedTenants = (Invoke-RestMethod -Headers @{Authorization = "Bearer $($myAccessToken.AccessToken)" } `
-Uri "https://management.azure.com/tenants?api-version=2020-01-01 " `
-Method Get).value
$federationTemplate = [pscustomobject][ordered]@{
defaultDomain = $null
customRegisteredDomains = $null
}
$outputResult = @()
foreach ($fedTenant in $myFederatedTenants) {
$fedDetails = $federationTemplate.PsObject.Copy()
$fedDetails.defaultDomain = $fedTenant.defaultDomain
$fedDetails.customRegisteredDomains = $fedTenant.domains
$outputResult += $fedDetails
}
$outputResult
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment