Diceyus
Diceyus

Reputation: 779

Getting Unauthorized from from Azure Web API

I created a basic project using Visual Studio 2015 Update 3 for Web API (nothing custom, bare bone) and deployed it to Azure (Free Account) following the instruction here. Then I created a Console client with the following code.

 public static async Task<bool> ReadValues()
    {
        try
        {
            // Authenticate the user and get a token from Azure AD
            //AuthenticationResult authResult = await AuthContext.AcquireTokenSilentAsync(Resource, ClientId);
            AuthenticationResult authResult = AuthContext.AcquireToken(Resource, ClientId, RedirectUri);

            // Create an HTTP client and add the token to the Authorization header
            HttpClient httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
                //"Bearer" 
                authResult.AccessTokenType
                , authResult.AccessToken);

            // Call the Web API to get the values
            var requestUri = new Uri(WebApiUri, "api/values");
            Console.WriteLine("Reading values from '{0}'.", requestUri);
            HttpResponseMessage httpResponse = await httpClient.GetAsync(requestUri);
            Console.WriteLine("HTTP Status Code: '{0}'", httpResponse.StatusCode.ToString());
            //Console.WriteLine("HTTP Header: '{0}'", httpClient.DefaultRequestHeaders.Authorization.ToString());
            if (httpResponse.IsSuccessStatusCode)
            {
                //
                // Code to do something with the data returned goes here.
                //
                var s = await httpResponse.Content.ReadAsStringAsync();
                Console.WriteLine(s);
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(httpResponse.ReasonPhrase);
            }
             return (httpResponse.IsSuccessStatusCode);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        return false;
    }

It works fine when I run the WEB API locally from the Visual Studio in debug, but when I deploy it to the Azure, it returns Unauthorized. Few common things that I might get asked:

  1. I do receive a valid bearer token
  2. I have created the App registrations in the Azure AD for bot hthe WEB API and the client
  3. The client and WEB API are using the correct redirect, resource uri
  4. The account I am using to login is the same as the one used to create the Azure account and it has full privileges in the domain/AD/API

On the API side, this is whole of the startup.auth.cs

using System.Configuration;
using System.IdentityModel.Tokens;
using Microsoft.Owin;
using Microsoft.Owin.Security.ActiveDirectory;
using Owin;
using WebApi;

[assembly: OwinStartup("default", typeof(Startup))]

namespace WebApi
{
    public partial class Startup
    {
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            app.UseWindowsAzureActiveDirectoryBearerAuthentication(
                new WindowsAzureActiveDirectoryBearerAuthenticationOptions
                {
                    Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
                    TokenValidationParameters = new TokenValidationParameters {
                         ValidAudience = ConfigurationManager.AppSettings["ida:Audience"]
                    },
                });
        }
    }
}

What else should I check?

Other references

https://www.simple-talk.com/cloud/security-and-compliance/azure-active-directory-part-3-developing-native-client-applications/

Upvotes: 2

Views: 1328

Answers (1)

Diceyus
Diceyus

Reputation: 779

Thanks for help from Juunas who provided me with a working copy, I was able to narrow down the cause. When I attached a debugger to the Azure instance of the Web API I was able to see a exception for Bad Audience. On trying to retrace my steps, I found that while deployment from Visual Studio, I was selection Enterprise Authentication in settings that was causing the web.config to change in way that lead to the problem. Not selecting that option, I was able to access the API through bearer token.

Upvotes: 0

Related Questions