This is a series of blog posts:
- Part 1: using PowerShell
- Part 2: using ADAL
- Part 3: using MSAL
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.