azureazure-active-directoryazure-ad-msalazure-authenticationeasy-auth

Get bearer token with MSAL.NET to access App Service with EasyAuth


I have an Azure App Service which is authenticated using Azure AD EasyAuth. Configured AppService with AD

Configured AppService with AD 2

I am trying to send a request from another App Service using C# and MSAL.NET (Microsoft.Identity.Client).

The authentication code looks like this

var app = ConfidentialClientApplicationBuilder
    .Create(config.ClientId) // The Client ID in the App Registration connected to the App Service
    .WithClientSecret(config.ClientSecret)
    .WithAuthority(new Uri(config.Authority)) // https://login.microsoftonline.com/tenant.onmicrosoft.com/v2.0
    .WithTenantId(config.TenantId) // Tenant Id Guid
    .Build();


// Used Scopes: ["https://graph.microsoft.com/.default"]
var credentials = await app.AcquireTokenForClient(config.Scopes)
    .ExecuteAsync(cancellationToken);

I get a bearer token successfully, but when I try to call the App Service with token injected to the headers I get a 401 and You do not have permission to view this directory or page. :(

Update 1:

I tried @Jim Xu answer and it's still giving me 401. It returns a www-authenticate header with the following value www-authenticate value

The resource id is the same ClientId in the App Reg

Update 2 - Solution

So to summarize the fix:

  1. The requested scopes when calling AcquireTokenForClient should include {Application ID Uri}/.default
  2. In EasyAuth configuration, the Allowed Token Audiences needs to be set to the Application ID Uri as well

Solution

  • If you want to call the Azure API app which enables easy auth, please refer to the following steps

    1. Get the Application ID URI of the AD application you use to enable easy auth

    a. In the Azure portal menu, select Azure Active Directory or search for and select Azure Active Directory from any page.

    b. Select App registrations > Owned applications > View all applications in this directory. Select your web app name, and then select Overview. enter image description here

    1. code
    var app = ConfidentialClientApplicationBuilder
        .Create(config.ClientId) // The Client ID in the App Registration connected to the App Service
        .WithClientSecret(config.ClientSecret)
        .WithAuthority(new Uri(config.Authority)) // https://login.microsoftonline.com/tenant.onmicrosoft.com/v2.0
        .WithTenantId(config.TenantId) // Tenant Id Guid
        .Build();
    
    
    // Used Scopes: ["{Application ID URI}/.default"]
    var credentials = await app.AcquireTokenForClient("{Application ID URI}/.default")
        .ExecuteAsync(cancellationToken);
    

    For more details, please refer to here.