Problem when i call a GET REQUEST with an AZURE Token, InvalidAuthenticationTokenAudience

Gonzalo ARRIBAS GORGOLAS 21 Reputation points
2021-07-20T13:15:09.217+00:00

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

Azure Monitor
Azure Monitor
An Azure service that is used to collect, analyze, and act on telemetry data from Azure and on-premises environments.
3,276 questions
Azure API Management
Azure API Management
An Azure service that provides a hybrid, multi-cloud management platform for APIs.
2,137 questions
Microsoft Authenticator
Microsoft Authenticator
A Microsoft app for iOS and Android devices that enables authentication with two-factor verification, phone sign-in, and code generation.
6,906 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,946 questions
Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
21,842 questions
0 comments No comments
{count} votes

Accepted answer
  1. AmanpreetSingh-MSFT 56,616 Reputation points
    2021-07-22T04:00:54.44+00:00

    Hi @Gonzalo ARRIBAS GORGOLAS · Thank you for reaching out.

    Looking at your code, you are making below call, for the resource https://management.azure.com.

    GET https://management.azure.com/subscriptions?api-version=2020-01-01  
    

    However, the token that you acquired is with the scope api://{clientId}/access_as_user, due to which you are getting InvalidAuthenticationTokenAudience error.

    To resolve the issue, you need to perform below steps:

    1. Navigate to Azure Active Directory > App Registrations > click on your app > API Permissions > +Add a permission > click on Azure Service Management > Delegated permissions > select checkbox for user_impersonation permission > Grant Admin consent.
      116932-image.png
    2. In your code, instead of using "api://{clientId}/access_as_user", use https://management.azure.com/user_impersonation scope.

    -----------------------------------------------------------------------------------------------------------

    Please "Accept the answer" if the information helped you. This will help us and others in the community as well.

    2 people found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Gonzalo ARRIBAS GORGOLAS 21 Reputation points
    2021-07-22T09:50:15.597+00:00

    Finally, it worked!
    Thank you so much! :D

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.