Cannot authorize to Azure API from Azure web application Azure AD authentication

Viewed 73

I have a web app hosted as an Azure app service that I am trying to authorize to an API also hosted as an Azure app service. I have registered both the app and the API, configured single-tenant AD authentication, authorized the client application, and have successfully obtained a bearer token. However, when I attempt to access a resources I receive a 401 error.

I've tried this using both delegated and application roles with no effect.

EDIT: Here is the code I'm using to obtain the token in my web app:

     var confidentialClient = ConfidentialClientApplicationBuilder.Create(<clientId>)
            .WithCertificate(<certificate>)
            .WithAuthority(<authority>)
            .Build();

     await app.AcquireTokenForClient(new string[] { "api://<app_id>/.default" });

EDIT: After parsing the JWT token I've confirmed that the application role is present; however the scopes are not. Seems this should not be a problem though.

What are some steps I can take to try to diagnose this authentication problem?

1 Answers

Please check the token used to call the web API. If the issuer has a v2 endpoint, then change "accessTokenAcceptedVersion" from null to 2 otherwise, keep it null or 1 .

enter image description here

Manifest in azure ad portal.

enter image description here

And make sure the scopes are granted admin consent by admin during authentication or through the portal:

enter image description here

  • 401 error Usually occurs due to audience mismatch. please check the allowed audiences parameter from https://resources.azure.com/ .
  • Navigate to your App Service resource > config > authsettings and correctly set the AllowAudiences value to the valid ones.
  • Audience should client id or app id URI for the app . It is used to check if token received is meant for the API you are trying to call.
  • AppIdUri of the app can be in the form api://<target_app_id> or "https://<site>.azurewebsites.net" And the clientIId of theapp.

authsettings :

"allowedAudiences":[
    https://<webapp_name>.azurewebsites.net/,
    api://<target_app_id>,
    client_id
      ]

Also tryin above, check scope by removing api:// prefix

Related