How to get Tenant ID from Subscription ID in Azure using PowerShell

This is a series of blog posts:

  • Part 1: using PowerShell
  • Part 2: using ADAL
  • Part 3: using MSAL

In order to do this, you’ll need:

  1. Call this Azure Resource Manager API without authentication, I suggest always use the latest stable API version
  2. Inspect the WWW-Authenticate header
  3. Parse the tenant id out of the authorization uri

Here’s a sample header value:

Bearer authorization_uri=”https://login.windows.net/e0a3d130-92db-4546-9813-45dd621f8379″, error=”invalid_token”, error_description=”The authentication failed because of missing ‘Authorization’ header.”

Here’s how to extract Tenant ID using PowerShell for Windows:

$hostName = 'management.azure.com'
$apiVersion = '2020-08-01'
$url = "https://$hostName/subscriptions/$subscription/?api-version=$apiVersion"
$response = try { Invoke-RestMethod -Method GET $url } catch [System.Net.WebException] { $_.Exception.Response }
$header = $response.Headers['WWW-Authenticate']
$match = $header | Select-String -Pattern 'Bearer authorization_uri="https://.+/(.+?)"'
$tenantId = $match.Matches[0].Groups[1].Value
$tenantId 

And using PowerShell Core, note a different exception type being caught:

$hostName = 'management.azure.com'
$apiVersion = '2020-08-01'
$url = "https://$hostName/subscriptions/$subscription/?api-version=$apiVersion"
$response = try { Invoke-RestMethod -Method GET $url } catch [System.Net.Http.HttpRequestException] { $_.Exception.Response }
$header = $response.Headers.WwwAuthenticate
$match = $header | Select-String -Pattern 'Bearer authorization_uri="https://.+/(.+?)"'
$tenantId = $match.Matches[0].Groups[1].Value
$tenantId 

When called with c3c0a359-4420-4f84-8925-f642e2717296 will output e0a3d130-92db-4546-9813-45dd621f8379.

That’s it, folks!

This entry was posted in Programming and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.