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