title: 401- Unauthorized authentication using REST API Dynamics CRM with Azure AD
body: <p>I'm trying to access a Dynamics CRM Online REST API with Azure AD oAuth 2 Authentication. In order to do so I followed these steps:<br/><br/>
  - I've registered a web application and/or web api in Azure<br/>
  - Configured the permissions to Dynamics CRM to have Delegated permissions "Access CRM Online as organization user"<br/>
  - And created a Key with a 1 year expiration and kept the Client ID generated.
  <br/><br/>
  After the web app was configured on Azure I have created a Console application in .NET/C# that uses ADAL to make a simple request, in this case to retrieve a list of accounts:
  <br/><br/></p>
  
  <pre><code>    class Program
  {
      private static string ApiBaseUrl = "https://xxxxx.api.crm4.dynamics.com/";
      private static string ApiUrl = "https://xxxxx.api.crm4.dynamics.com/api/data/v8.1/";
      private static string ClientId = "2a5dcdaf-2036-4391-a3e5-9d0852ffe3f2";
      private static string AppKey = "symCaAYpYqhiMK2Gh+E1LUlfxbMy5X1sJ0/ugzM+ur0=";
  
      static void Main(string[] args)
      {
          AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(ApiUrl)).Result;
  
          var clientCredential = new ClientCredential(ClientId, AppKey);
  
          var authenticationContext = new AuthenticationContext(ap.Authority);
          var authenticationResult = authenticationContext.AcquireToken(ApiBaseUrl, clientCredential);
  
          var httpClient = new HttpClient();
          httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken);
  
          var result = httpClient.GetAsync(Path.Combine(ApiUrl, "accounts")).Result;         
      }
  }
  </code></pre>
  
  <p>I retrieve an access token successfully but when I try to do a httprequest to CRM I always get a <strong>401 - Unauthorized status code</strong>. What am I missing?</p>