Dynamics CRM 2016 Online Rest API with client credentials OAuth flow
Asked Answered
C

1

6

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;
Clef answered 2/5, 2016 at 20:41 Comment(3)
Similar to #37216242 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.Cally
Please see the solution to my similar question #37455039Iloilo
Possible duplicate of Using ADAL C# as Confidential User /Daemon Server /Server-to-Server - 401 UnauthorizedQuirinal
G
0

You need to add an "Application user" and assign a custom Security Role in CRM. See my answer in https://mcmap.net/q/865484/-401-unauthorized-authentication-using-rest-api-dynamics-crm-with-azure-ad

Gale answered 1/2, 2018 at 3:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.