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.1" />

Then use one of its helper methods:

using Microsoft.Identity.Client;

var hostName = "";
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");


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:

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: Logo

You are commenting using your 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.