I'm trying to authenticate with Dynamics CRM 2016 Online and Azure Active Directory. I was able to follow all the steps here:
https://msdn.microsoft.com/en-us/library/mt622431.aspx and https://msdn.microsoft.com/en-us/library/gg327838.aspx
but these steps demonstrate how to set-up username authentication flow. I would like to use the client credentials flow. I created a new app in Azure AD - a web application. I have a client ID and an app key and I set-up the permissions for Dynamics CRM Online. I'm able to get the access token, but on subsequent calls I get this error:
HTTP Error 401 - Unauthorized: Access is denied
Is there a step I missed? Does anybody know of a post somewhere that provides details on how to get this flow working?
Here is my code:
string clientId = "<client id>";
string appKey = "<app key>";
// Get the authority and resource URL at runtime
AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync(new Uri("https://<org address>/api/data/")).Result;
String authorityUrl = ap.Authority;
String resourceUrl = ap.Resource;
// Authenticate the registered application with Azure Active Directory.
AuthenticationContext authContext = new AuthenticationContext(authorityUrl);
ClientCredential clientCredential = new ClientCredential(clientId, appKey);
AuthenticationResult result = authContext.AcquireToken(resourceUrl, clientCredential);
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpResponseMessage response = client.GetAsync("https://<org address>/api/data/v8.1/EntityDefinitions").Result;