I have a .NET desktop application where I login with my Microsoft account (username and email). When I do that, I obtain an access token. Then, I want to display in the CONSOLE the list of subscriptions I have activated in that account. I am using a GET REQUEST, which is the only thing I have found in the documentation of Azure SDK for .NET developers.
class Program
{
public static string clientId = "XXXXXXXXXXXXXXXXXXXXXX";
public static string tenantId = "XXXXXXXXXXXXXXXXXXXXXX";
public static IPublicClientApplication PublicClientApp;
static void Main(string[] args)
{
GetATokenForGraph().GetAwaiter().GetResult();
}
static async Task GetATokenForGraph()
{
var options = new PublicClientApplicationOptions();
options.ClientId = clientId;
options.AzureCloudInstance = AzureCloudInstance.AzurePublic;
options.TenantId = tenantId;
PublicClientApp = PublicClientApplicationBuilder.CreateWithApplicationOptions(options)
.WithRedirectUri("https://login.microsoftonline.com/common/oauth2/nativeclient")
.Build();
var _scopes = new string[] { $"api://{clientId}/access_as_user" }.AsEnumerable();
var authResult = await PublicClientApp.AcquireTokenInteractive(_scopes)
.ExecuteAsync();
Console.WriteLine("Username: " + authResult.Account.Username);
Console.WriteLine("Environment: " + authResult.Account.Environment);
Console.WriteLine("Scope: " + authResult.Scopes.FirstOrDefault());
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = AuthenticationHeaderValue.Parse(authResult.CreateAuthorizationHeader());
const string environmentsUri = "https://management.azure.com/subscriptions?api-version=2020-01-01";
var response = httpClient.GetAsync(environmentsUri).Result;
var content = response.Content.ReadAsStringAsync().Result;
Console.WriteLine("\nContent HTTP request:\n");
Console.WriteLine(content);
}
}
XXXXXXXXXXXXXXXXXX is my clientID.
However, when I execute the code and I print the content, I get this error:
{"error":{"code":"InvalidAuthenticationTokenAudience","message":"The access token has been obtained for wrong audience or resource 'XXXXXXXXXXXXXXXXXXXXXXXXXXX'. It should exactly match with one of the allowed audiences 'https://management.core.windows.net/','https://management.core.windows.net','https://management.azure.com/','https://management.azure.com'."}}
I did all the steps to register my application as in https://learn.microsoft.com/es-es/azure/active-directory/develop/scenario-protected-web-api-app-registration