This is a series of blog posts:
In order to do this, you’ll need:
- Call this Azure Resource Manager API without authentication, I suggest always use the latest stable API version
- Inspect the WWW-Authenticate header
- 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!