401 error when authenticating to an Azure API App using AAD

别等时光非礼了梦想. 提交于 2019-12-04 06:12:20

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 }
                }
            }
        );
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!