Dynamics 365 CE and Azure Function Part 3

This is our third article in the Dynamics 365 and Azure series, in first article we discussed basic introduction about azure function and set azure function app. In second article we discussed how we can connect to Dynamics 365 organization using hard coded user name and password. Today we are going to discuss how we can get rid of hard coded credentials and use server to server authentication.

To implement server to server authentication we need three following things
First we need to get tenant id so login to Azure portal and navigate to Azure Active Directory -> Properties and note down Directory ID
Once we got our tenant id, now we need to get application id and key details. We need application id to setup application user in Dynamics 365. To get these details we need to register app in Azure Active Directory, so now navigate to Azure Active Directory and click on New application registration

Provide your app details and click on Create

Once application registration is created and note down Application ID
Go to Dynamics 365 organization and navigate to Settings->Security-> Users and change view to Application Users. Click on New button to add application user, Make sure Application User form is selected, use application id we copied from the Azure portal, provide email address and create application user. Once user is created add required security role for this user.
Next we need never expire key for our application. Click on Settings -> Keys and add a nearexpire key
Now we have all required information ready, we can use these details in our following code in our Azure function trigger.

 private static OrganizationWebProxyClient GetCRMService() {

  var aadInstance = "https://login.microsoftonline.com/";
  var organizationUrl = "https://yourDynamicsCRM.crm.dynamics.com"; 

  var tenantId = "aeb....";

  var applicationId = "c86...";

  var key = "7jNY.....";

  var clientcred = new ClientCredential(applicationId, key);

  var authenticationContext = new AuthenticationContext(aadInstance + tenantId);

  var authenticationResult = authenticationContext.AcquireTokenAsync(organizationUrl, clientcred);

  var requestedToken = authenticationResult.Result.AccessToken;

  var sdkService = new OrganizationWebProxyClient(new Uri(organizationUrl +
			@"/xrmservices/2011/organization.svc/web?SdkClientVersion=8.2"), false);
  sdkService.HeaderToken = requestedToken;

  return sdkService;

Now we can update our code to use OrganizationWebProxyClient method like following.

OrganizationWebProxyClient service = GetCRMService();

We also need to add following reference to use OrganizationWebProxyClient in our Azure function trigger.

using Microsoft.Xrm.Sdk.WebServiceClient;

Dynamics 365 CE and Azure Function Part 1
Dynamics 365 CE and Azure Function Part 2

Leave a Reply

Your email address will not be published. Required fields are marked *