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

This is a series of blog posts:

First you need to install AAD client NuGet package. Note this is MSAL, the modern and recommended way to communicate with AAD.

<PackageReference Include="Microsoft.Identity.Client" Version="4.36.2" />

Then use one of its helper methods:

using Microsoft.Identity.Client;
using Microsoft.Identity.Client.Instance;

var hostName = "management.azure.com";
var apiVersion = "2020-08-01";
var requetUrl = $"https://{hostName}/subscriptions/{subscription}?api-version={apiVersion}";
var httpClient = new HttpClient();
var response = await httpClient.GetAsync(requetUrl, cancellationToken);

var authenticationParameters = WwwAuthenticateParameters.CreateFromResponseHeaders(response.Headers);

var authorizationHeaderRegex = new Regex(@"https://.+/(.+)/?", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
var match = authorizationHeaderRegex.Match(authenticationParameters.Authority);
var tenantString = match.Success ? match.Groups[1].Value : null;

if (!Guid.TryParse(tenantString, out var tenantId))
{
    throw new InvalidOperationException($"Received tenant id '{tenantString}' is not valid guid");
}

Console.WriteLine(tenantId);

It’s not async and makes you to write less code. You still need to parse the tenant id out of the authorization uri, though.

You can find the code here: https://dotnetfiddle.net/Wyh9vs.


However after I contributed to the library, starting version 4.37.0, parsing using Regex is not needed anymore:

using Microsoft.Identity.Client;

var hostName = "management.azure.com";
var apiVersion = "2020-08-01";
var requetUrl = $"https://{hostName}/subscriptions/{subscription}?api-version={apiVersion}";
var httpClient = new HttpClient();
var response = await httpClient.GetAsync(requetUrl, cancellationToken);

var authenticationParameters = WwwAuthenticateParameters.CreateFromResponseHeaders(response.Headers);
var tenantId = authenticationParameters.GetTenantId();

Console.WriteLine(tenantId);

You can find the updated, shorter code here: https://dotnetfiddle.net/EYkWAg.

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 )

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.