401 error when authenticating to an Azure API App using AAD 401 error when authenticating to an Azure API App using AAD azure azure

401 error when authenticating to an Azure API App using AAD


Your problem have something to do with the valid audiences. You may have 2 choices:

Option 1. Try to acquire the token with the WebAPI client ID as the AcquireToken method 'resource' parameter, instead of its Uri.

Option 2. If the previous method didn't work, you should have to modify the authentication settings of the App Service API, using Azure Resources Explorer. Navigate to your web API, find the authSettings JSON document under the config node, and modify (after having changed to Read/Write mode) the array allowedAudiences to match your needs. In your case you may have to change http to https


In my ASP.NET 4.5 Web app I found that I had to specify the Valid Audiences to avoid a runtime exception being thrown.

public partial class Startup{    private static string _aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];    private static string _tenant = ConfigurationManager.AppSettings["ida:Tenant"];    private static string _realm = ConfigurationManager.AppSettings["ida:Wtrealm"];    private static string _metadataAddress = string.Format("{0}/{1}/federationmetadata/2007-06/federationmetadata.xml", _aadInstance, _tenant);    private static string _authority = String.Format(CultureInfo.InvariantCulture, _aadInstance, _tenant);    public void ConfigureAuth(IAppBuilder app)    {        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);        app.UseCookieAuthentication(new CookieAuthenticationOptions());        app.UseWsFederationAuthentication(            new WsFederationAuthenticationOptions            {                Wtrealm = _realm,                MetadataAddress = _metadataAddress,                TokenValidationParameters = new TokenValidationParameters                {                    ValidAudiences = new string[] { "spn:" + _realm }                }            }        );    }}