Azure AD Authentication 401 error "the audience is invalid" AddAzureADBearer .Net Core Web Api

The problem was the configuration data for the Web API. When they say the ClientId what they really want is the value under the "expose an API" option where it says "Application ID URI". What I was putting in there was the guid for the Web Api application registration. Below is how it should look.

  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "myportal.onmicrosoft.com",
    "TenantId": "mytenant-guid",
    "ClientId": "https://myportal.onmicrosoft.com/test_core_web_api_spa"
  },

Note on the API format. It appears that when you register the application directly in Azure the format for the exposed API will be api://app-guid. But if you first create your application using Visual Studio then the format will default to something like https:///myportal.onmicrosoft.com/project-name-in-visual-studio.


Like most people here I was stuck on this for a little while and the documentation seriously lets it down.

While following the MS guide it populates appsettings file in the Server project like so

"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "contoso.onmicrosoft.com",
"TenantId": "e86c78e2-8bb4-4c41-aefd-918e0565a45e",
"ClientId": "41451fa7-82d9-4673-8fa5-69eff5a761fd",
 }

Frustratingly this fix is as simple as pre-fixing the client ID with api:// so that it matches both the audience in the JWT and the Application ID URI on the Expose an API section of your server app in AAD

"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "contoso.onmicrosoft.com",
"TenantId": "e86c78e2-8bb4-4c41-aefd-918e0565a45e",
"ClientId": "api://41451fa7-82d9-4673-8fa5-69eff5a761fd",
} 

enter image description here