21

I have create a webapi secured with azure active directory. I need to test this now and trying to use fiddler with an authorization header. I am trying to generate the token with below code.

Target obj = (Target)cmbTarget.SelectedItem;

AuthenticationResult authenticationResult;
string aadInstance = obj.AADInstance; // "https://login.windows.net/{0}";
string tenant = obj.Tenant; //"rudderless.onmicrosoft.com";
string apiResourceId = obj.ApiResourceId; //"15b4ac7f-23a8-4958-96a5-64159254690d";
string clientId = obj.ClientId; // "47cdc6c3-226a-4c38-b08e-055be8409056";

Uri redirectUri = new Uri(obj.RedirectUri); //new Uri("http://nativeclient");
string authority = string.Format(aadInstance, tenant);
authContext = new AuthenticationContext(authority);

authenticationResult = this.authContext.AcquireToken(apiResourceId, 
                            clientId, redirectUri, PromptBehavior.Always);

txtToken.Text = authenticationResult.AccessToken;
Clipboard.SetText($"Bearer {txtToken.Text}");

I get the token generated successfully and when I am using the token to call the webapi it throwing 401 with message

WWW-Authenticate: Bearer error="invalid_token", error_description="The audience is invalid"

4

10 Answers 10

29

I think it is important to revisit the different steps of authentication, and hopefully through the discussion you will be able to solve the issue you are having.

When a client is trying to get an access token to a resource, it needs to specify to AAD which resource it wants to get a token for. A client may be configured to call multiple resources, all with different configurations, so it is an expectation that the resource is always specified in an Access Token Request.

The resource can either be an App ID GUID for the Resource, or a valid App ID URI which is registered on the Resource. AAD should be able to uniquely identify which resource you are trying to reach based on the value you provide. However, note that if you use an App ID GUID, you will get a token from AAD where the Audience claim is the App ID GUID. Alternatively, if you use an App ID URI, you will see that URI as the audience claim in the token.

In both situations, you will get a token for the 'same' resource, but the claim in the token will appear differently. Additionally, it may be possible that a single application resource may have multiple App ID URIs registered on their app. Depending on which one you use in the authentication request, you will get a different audience claim in the token which matches the resource parameter you passed in.

Finally, once you get the token, you send it over to the Resource API who will validate the token for a number of things, such as: the Client ID Claim, the Scopes/Roles Claims, the authentication method ('acr' claim), and definitely that the audience claim matches what they expect!

This means that the Resource API ultimately needs to say "I accept < App ID GUID > as a valid Audience Claim"... or "I accept < App ID URI > as a valid Audience Claim". This kind of logic may be built into the library you are using (like OWIN), but you need to make sure that on your API side, you have it configured correctly for the Audiences you expect. You could, if you wanted, make it so that your API does not check the Audience claim at all! All the claims in the token are plaintext, and thus you could really do whatever you want, but you would not have a very secure API in that situation :]

End of the day, my hunch is that this error is coming from your own API, and it is happening because you have not configured your app to accept an Audience claim which matches your Resource's App ID GUID (which it looks like what you are passing when you are getting a token based on your code sample).

I hope this solves your issue!

1
  • 1
    I started to learn AAD recently. This answer explains things in such easy to understand and concise words, better than almost all official docs I have read. Thank you!
    – ZZY
    Nov 21, 2019 at 7:23
22

Problem

After implementing the instructions found in this Protected web API: Code configuration article, I received an error message similar to the OP's:

WWW-Authenticate: Bearer error="invalid_token", error_description="The audience is invalid"

The problem turned out to be my AzureAd > ClientId setting in my appsettings.json file.

Solution

I updated the appsettings.json file of my ASP.NET Core Web API app so that the ClientId setting used the "Application ID URI" found in portal.Azure.com under my App Registriation > "Expose An API" section.

enter image description here

The section in appsettings.json looks similar to this:

"AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "TenantId": "XXXXXXXX-XXXXX-XXXXX-XXXXX-XXXXXXXXXX",
    // ClientId = Portal.Azure.com > App Registration > Expose an API > "Application ID URI"
    "ClientId": "api://XXXXX-XXXXXX-XXXXX-XXXX-XXXXXXXXX"   
}
4
  • 1
    This helped me, with a twist. Turns out the uri is case sensitive. So copying it from the page shown above solved my issue.
    – ILOABN
    Aug 26, 2020 at 9:12
  • 1
    This helped me as well! Microsoft's documentaion and current Blazor wasm templates doesn't generate the ClientId properly. Source: learn.microsoft.com/en-us/aspnet/core/blazor/security/…
    – diegorodny
    Oct 19, 2020 at 23:50
  • 1
    I have been staring at this for two days and it was fixed my issue as well!
    – Kameron
    Nov 9, 2020 at 2:03
  • This also saved me!
    – sugarcane
    Jul 26 at 6:30
13

Important note

"aud" value that is being generated for JWT token by azure is also controlled by "accessTokenAcceptedVersion" property in AD application manifest.

This property defines a version of the access token that will be generated (MS docs about accessTokenAcceptedVersion).

Possible results for its values:

  • null or 1 - "api://" prepended to GUID
  • 2 - "api://" is not added, so there should be GUID only
11

I had the same issue. Thought of sharing it. I have change the Web Api Audience to the ClientId of the Web App. After this it works.

The Microsoft references show the following example:

{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "ClientId": "[Client_id-of-web-api-eg-2ec40e65-ba09-4853-bcde-bcb60029e596]",
    "TenantId": "common",
    "Audience": "custom App ID URI for your web API"
  },
  // more lines
}
2
  • 16
    Can you tell me where exactly you did that ?
    – Ron16
    Oct 25, 2017 at 15:27
  • 3
    @Ron16 it is in appsettings.json. If you have set the access token accepted version to 2, or for Azure AD B2C web APIs then the client id and audience needs to be same (i.e. no need to write api://) source: learn.microsoft.com/en-us/azure/active-directory/develop/…
    – suomi-dev
    May 19, 2021 at 11:37
5

Can also be that your app/lib is using a newer version of the api. If accessTokenAcceptedVersion is null in the manifest of your app ms defaults to v1. Check your jwt token in http://jwt.io If you get this - check your JWT Token. If ISS isn't like this

 "iss": "https://login.microsoftonline.com/[yadyada]/v2.0",

then most likely you're using another version (like version 1 which is default). Check the manifest of your azure ad app: Below value is probably null or one, should be two:

"accessTokenAcceptedVersion": 2,
2
  • 1
    Spent hours trying to figure this problem out and this was the issue. In my case, accessTokenAcceptedVersion was null (in the Web API manifest). I set it to 2 (matching the version) and it worked. Thanks!
    – Don Fitz
    May 19, 2021 at 21:50
  • This resolved my issue, I also spent hours time to investigate the issue, and when I changed that value to 2, it works. I believe the issue is the Aad issues the version 1 token, but your MSAL library only can verify version 2 token, that is the discrepancy. I think this mismatch issue is not brought to enough attention by Microsoft Documentation at this time.
    – IcyBrk
    Jan 8, 2022 at 22:34
1

I had the same issue. I was using the client's Resource ID as the parameter for AcquireToken when I should have used the server's Resource ID.

It works when I use the correct Resource ID.

1
  • Excellent! Seems obvious now that I read your comment. This is working for me now. Thanks :)
    – MikeSmith
    Aug 2, 2021 at 21:42
1

I got the same error. It was because I was using a custom domain, so my API ID URL wasn't api://{client-id}.

The solution is to set the Audience setting on your appsettings.json, just like mentioned in the Microsoft Wiki:

"AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "TenantId": "XXXXXXXX-XXXXX-XXXXX-XXXXX-XXXXXXXXXX",
    "ClientId" : "XXXXXXXX-XXXXX-XXXXX-XXXXX-XXXXXXXXXX",
    // Audience = Portal.Azure.com > App Registration > Expose an API > "Application ID URI"
    "Audience": "Application ID URI"   
}
1
  • That was exactly my issue.
    – Joao Leal
    Mar 17, 2022 at 11:04
1

In my case the situation was very deceiving. The aud property in the bearer token was the correct api://{guid} but the app was still throwing a 401. It turns out my application transforms were not operating correctly so my app was in fact not passing the correct client id to azure active directory. Upon digging further in .net 6, publishing an app does not actuate the transform process like earlier versions of .net. Instead, the framework relies on reading the ASPNETCORE_ENVIRONMENT application setting in azure to decide which config file to use. If it doesn't exist the app defaults to the appsettings.json file. I added this property and the setting 'Release' and the app read the correct appsettings.release.json file and the 401 went away. Hopefully this helps someone as I spent frustrating days on this issue.

TLDR: Check that your app is actually reading the correct config file with the correct tenant id, client id

0

While calling api for implementing service principle through App registration in active directory. I got this error while calling api-GET {vaultBaseUrl}/secrets/{secret-name}/{secret-version}?api-version=7.0 with bearer key to get key vault secret value. As part of fix, to get bearer value, Apart from passing clientid, client secret, grant_type,I added resource key with value https://vault.azure.net as part of request body of api call for https://login.microsoftonline.com/{ActiveDirectoryId}/oauth2/token.

0

This might help someone: I've encountered this error because the MS Graph User.Read permission was missing on the SharePoint Online Client Extensibility Web Application Principal. Out of the box, this app reg already has the User.Read permission, but I had removed that one because (for an earlier project) I already used User.Read.All, thinking that it included User.Read. However, User.Read is used for sign-in purposes while User.Read.All is not. When I restored User.Read, my problem was solved.

Quite the unintuitive solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.