title: 401 when accessing Dynamics CRM 2016 Web APIs
body: <p>I am struggling to access the <strong>Dynamics 2016 CRM OData Web APIs</strong> from a console application.</p>
  
  <p>We have <strong>Dynamics CRM 2016</strong> installed, configured with <em>Claims-based authentication</em>, and using AD FS v3.0. </p>
  
  <p>My understanding is that a console app (or web app) should be able to access the Web APIs using Windows integrated authentication (i.e. NTML or Kerberos) without any special treatment ... or maybe the OAuth flow should work when enabled.</p>
  
  <p>For a regular user accessing Dynamics "pages", the authentication works fine (redirection to AD FS log in page), but accessing the OData APIs does not seem to work (for instance : <a href="https://crm.domain.org/api/discovery/v8.0/" rel="noreferrer">https://crm.domain.org/api/discovery/v8.0/</a> ) : </p>
  
  <ul>
  <li>in a browser I get a Windows login prompt and typing valid credentials always results in a HTTP 401 unauthorized error</li>
  <li>in a brower, if I navigate to a Web API url <strong>after</strong> having logged on on the pages , then I can access the Web APIs (i.e. some cookies must be set and I am already implicitly authorized)</li>
  <li>from code, using an HttpClient with specific valid credentials (or current credentials) , I also get a 401</li>
  </ul>
  
  <p>Things I have tried : </p>
  
  <ul>
  <li>if I <strong>disable Claims-based authentication completely</strong> , HttpClient works fine and I can access the OData APIs</li>
  <li><p>if I leave Claims-based authentication enabled, and <strong>activate OAuth</strong> via PowerShell <code>Add-PSSnapin Microsoft.Crm.PowerShell ; $ClaimsSettings = Get-CrmSetting -SettingType OAuthClaimsSettings; $ClaimsSettings.Enabled = $true ; Set-CrmSetting -Setting $ClaimsSettings ;</code>. </p>
  
  <p>Windows integrated authentication still does not work, but using Bearer authentication is now possible. I can use <a href="https://msdn.microsoft.com/en-us/library/dn531009.aspx#Anchor_6" rel="noreferrer">this snippet</a> to retrieve the OAuth Endpoint for token generation, and use <a href="https://msdn.microsoft.com/en-us/library/microsoft.identitymodel.clients.activedirectory.authenticationcontext.acquiretokenasync.aspx" rel="noreferrer"><code>AuthenticationContext.AcquireTokenAsync</code></a> to issue a token, and then pass it in the <code>Authorization</code> HTTP Header ... but then, no matter what, I get this error : </p>
  
  <p><code>Bearer error=invalid_token, error_description
  =Error during token validation!, authorization_uri=https://our.adfs.domain.org/adfs/oauth2/authorize, resource_id=https://crm.domain.org/</code></p></li>
  </ul>
  
  <p>Am I missing something ? is that possibly a configuration issue ? </p>