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

This is a series of blog posts:

In previous part we did it this using a script, this time we’ll do it using C#.

First you need to install AAD client NuGet package. Note this is ADAL, it’s now legacy and put into the maintenance mode.

<PackageReference Include="Microsoft.IdentityModel.Clients.ActiveDirectory" Version="5.2.9" />

Then use one of its helper methods:

using Microsoft.IdentityModel.Clients.ActiveDirectory;

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 = await AuthenticationParameters.CreateFromUnauthorizedResponseAsync(response);

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);

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

One of the drawbacks is that the helper method is async without a real need to be: underneath it calls another async helper which reads the content of the response but then it doesn’t use the content.

So you can write little more code yourself without the penalty of making it async:

using Microsoft.IdentityModel.Clients.ActiveDirectory;

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 = AuthenticationParameters.CreateFromResponseAuthenticateHeader(response.Headers.WwwAuthenticate.ToString());

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);

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

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.