6
votes

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;
1
Similar to stackoverflow.com/questions/37215742/… It could be possible that their API does not support application creds. May be they are looking for specific permission (granted by delegated access) that doesn't exist in the access token acquired by credentials flow.Frank Q.
Please see the solution to my similar question stackoverflow.com/questions/37454539/…IntegerWolf

1 Answers

0
votes

You need to add an "Application user" and assign a custom Security Role in CRM. See my answer in https://stackoverflow.com/a/48554845/3799784