Amr Elsehemy
Amr Elsehemy

Reputation: 1033

ASP.NET API returns Authorization has been denied for this request on localhost but works normally on Azure

[Authorize]
    public class ValuesController : ApiController
    {
        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "Simple" , "Test"};
        }
}

This is a simple "Web API 2" app.

public void ConfigureAuth(IAppBuilder app)
        {
            app.UseWindowsAzureActiveDirectoryBearerAuthentication(
              new WindowsAzureActiveDirectoryBearerAuthenticationOptions
              {
                  Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
                  TokenValidationParameters = new TokenValidationParameters
                  {
                      SaveSigninToken = true,
                      ValidAudience = ConfigurationManager.AppSettings["ida:Audience"]
                  },
              });
        }

As shown the application is using the WindowsAzureActive Directory authentication and Authorization.

Note that it works normally when published to Azure Api App, but always denies the request when in localhost.

I am not sure what happened, it used to work before.

Regards

Upvotes: 1

Views: 1643

Answers (1)

vibronet
vibronet

Reputation: 7394

Normally this is due to a mismatch in the audience you expect in the web API (the value you set via ValidAudience) and what you get in the incoming token. The value in the token reflects the resource identifier you used when requesting the token from the client. Do you change the client code to request a different audience when calling the localhost instance vs the Azure API one? Also, how do you publish the API to Azure? If you use VS, and in the Publish wizard settings you have the checkbox "use organizational auth" checked, the deployed web API will have a different audience value in its web.config.

Upvotes: 1

Related Questions