Getting your AAD Tenant Id without authentication!

Getting your AAD Tenant Id without authentication!

Another quick post - I’ve been doing some work with silent configuration of OneDrive and the new Known Folder Migration GPO solution all being deployed via Intune for multiple clients.

One thing that is required for the KFM solution is the Azure Tenant Id. Being the nerd I am, I wanted to see if I could get the Id without having to log in to the tenant.

After a quick search, I found this great article written by Tao Yang which talks about the open REST endpoints that return valuable information on your AAD tenant!

Since Tao posted his findings, Microsoft has updated the endpoints to improve and simplify the authentication flow.

So with the findings of Tao & the updated endpoint info, below is a simple function to retrieve the Azure AD Tenant Id via the client domain!

function Get-TenantIdFromDomain {
    param (
        [Parameter(Mandatory = $true)]
        [string]$FQDN
    )
    try {
        $uri = "https://login.microsoftonline.com/$($FQDN)/.well-known/openid-configuration"
        $rest = Invoke-RestMethod -Method Get -UseBasicParsing -Uri $uri
        if ($rest.authorization_endpoint) {
            $result = $(($rest.authorization_endpoint | Select-String '\w{8}-\w{4}-\w{4}-\w{4}-\w{12}').Matches.Value)
            if ([guid]::Parse($result)) {
                return $result.ToString()
            }
            else {
                throw "Tenant ID not found."
            }
        }
        else {
            throw "Tenant ID not found."
        }
    }
    catch {
        Write-Error $_.Exception.Message
    }
}

Now, if I run the function against my own Azure Tenant..

Get-TenantIdFromDomain -FQDN "powers-hell.com"

Successfully captured GUID

There we have it! A very simple way to programmatically retrieve the Id of your AAD Tenant. Now that I have this information I can implement it in my OneDrive KFM solution - which of course will be published here once it’s done!

As always, code from today’s post will be available on my GitHub & I am always keen to discuss anything PowerShell related on Twitter.