title: Azure web api Unauthorized 401
body: <p>I have some code that used to call Azure Scheduler to get a token,  then using that token, make restful calls.  Works a treat.</p>
  
  <p>So i decided to adopt the code into a new app but this time call my own web api hosted on azure. The API is registered in Active directory I have created a secret key etc.  When i initiliaze my static httpclient it fetches a token succesfully.</p>
  
  <p>But when i make a call to the API using the token for auth, the response is a 401 "unauthorized",  below is the code.</p>
  
  <pre><code> public static class SchedulerHttpClient
  {
      const string SPNPayload = "resource={0}&amp;client_id={1}&amp;grant_type=client_credentials&amp;client_secret={2}";
  
      private static Lazy&lt;Task&lt;HttpClient&gt;&gt; _Client = new Lazy&lt;Task&lt;HttpClient&gt;&gt;(async () =&gt;
      {
          string baseAddress = ConfigurationManager.AppSettings["BaseAddress"];
          var client = new HttpClient();
          client.BaseAddress = new Uri(baseAddress);
          await MainAsync(client).ConfigureAwait(false);
          return client;
      });
  
      public static Task&lt;HttpClient&gt; ClientTask =&gt; _Client.Value;
  
      private static async Task MainAsync(HttpClient client)
      {
          string tenantId = ConfigurationManager.AppSettings["AzureTenantId"];
          string clientId = ConfigurationManager.AppSettings["AzureClientId"];
          string clientSecret = ConfigurationManager.AppSettings["AzureClientSecret"];
  
          string token = await AcquireTokenBySPN(client, tenantId, clientId, clientSecret).ConfigureAwait(false);
  
          client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token); //TODO ssmith: const or localization
      }
  
      private static async Task&lt;string&gt; AcquireTokenBySPN(HttpClient client, string tenantId, string clientId, string clientSecret)
      {
          var payload = String.Format(SPNPayload,
                                      WebUtility.UrlEncode(ConfigurationManager.AppSettings["ARMResource"]),
                                      WebUtility.UrlEncode(clientId),
                                      WebUtility.UrlEncode(clientSecret));
  
          var body = await HttpPost(client, tenantId, payload).ConfigureAwait(false);
          return body.access_token;
      }
  
      private static async Task&lt;dynamic&gt; HttpPost(HttpClient client, string tenantId, string payload)
      {
          var address = String.Format(ConfigurationManager.AppSettings["TokenEndpoint"], tenantId);
          var content = new StringContent(payload, Encoding.UTF8, "application/x-www-form-urlencoded");
          using (var response = await client.PostAsync(address, content).ConfigureAwait(false))
          {
              if (!response.IsSuccessStatusCode)
              {
                  Console.WriteLine("Status:  {0}", response.StatusCode);
                  Console.WriteLine("Content: {0}", await response.Content.ReadAsStringAsync().ConfigureAwait(false));
              }//TODO: start removing tests
  
              response.EnsureSuccessStatusCode();
  
              return await response.Content.ReadAsAsync&lt;dynamic&gt;().ConfigureAwait(false);
          }
      }
  }
  </code></pre>
  
  <p>The above code is the class that creates a httpclient and gets its authorization.</p>
  
  <pre><code>public virtual async Task&lt;T&gt; GetAsync(string apiURL)
      {
          try
          {
              _client = await SchedulerHttpClient.ClientTask;
              var response = await _client.GetAsync(apiURL);
              response.EnsureSuccessStatusCode();
              var responseContent = await response.Content.ReadAsAsync&lt;T&gt;().ConfigureAwait(false);
  
              return responseContent;
          }
          catch (Exception e)
          {
              return default(T);
          }
      }
  </code></pre>
  
  <p>The above code is a quick lift of my old code simply to test if i can get any results. but as stated it returns a 401.</p>
  
  <p>My question is, is my old code to get authorization incorrect?</p>
  
  <pre><code>&lt;add key="ARMResource" value="https://management.core.windows.net/" /&gt;
  &lt;add key="TokenEndpoint" value="https://login.windows.net/{0}/oauth2/token" /&gt;
  &lt;add key="BaseAddress" value="https://mysite.azurewebsites.net" /&gt;
  </code></pre>