Thanks everyone for your answers. I finally managed to access Dynamics CRM OData API using ADAL 3.
Since many people are still having problems doing this, see the following steps:
App registration
Log into portal.azure.com
using your Office 365 administrator user of your Dynamics CRM subscription.
Go to Azure Active DirectorApp registrations and add New application registrations
Enter "Name" and "Sign-on URL", the URL could be anything (https://localhost for example)
Select the registered app you just created, go to SettingsKeys
Enter a key description, click Save and copy the Value (and keep it since you will need it later). Also copy the Application ID of the registered app.
Go to "Required Permissions", click Add, select "Dynamics CRM Online" then tick "Access CRM Online as organisation users".
These steps enable a client application to access Dynamics CRM by using the Application ID and the client secret you created in step 5.
Your client application is now able to be authenticated against Azure AD with permission to access CRM Online. However, CRM Online does not know about this "client application" or "user". CRM API will response a 401 if you try to access it.
Add CRM application user
To let CRM know about the "client application" or "user", you'll need to add an application user.
Go to CRMSecurity Roles, create a new Security Role or just copy the "System Administrator" Role
Go to CRMSettingsSecurityUsers, create a new User, change the form to "Application User"
Enter the required fields with the Application ID that you have in previous step. Once saved, CRM will auto populate the Azure AD Object ID and the URI.
Add the user to the Security Role created from previous step.
Now you should be able to access CRM API using HttpClient and ADAL using the sample code below:
var ap = await AuthenticationParameters.CreateFromResourceUrlAsync(
new Uri("https://*****.api.crm6.dynamics.com/api/data/v9.0/"));
String authorityUrl = ap.Authority;
String resourceUrl = ap.Resource;
var authContext = new AuthenticationContext(authorityUrl);
var clientCred = new ClientCredential("Application ID", "Client Secret");
var test = await authContext.AcquireTokenAsync(resourceUrl, clientCred);
Console.WriteLine(test.AccessToken);
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", test.AccessToken);
var response = await client.GetAsync("https://*****.api.crm6.dynamics.com/api/data/v9.0/contacts");
var contacts = await response.Content.ReadAsStringAsync();
Console.WriteLine(contacts);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…