I have been working on an integraiton project for Dynamics CRM since last month and I learned some lessons from the work I did and would like to share them here.

Background

The background is the Dynamics CRM (it is called Dynamics 365 now) use the Azure Active Directory as its user management database. Hence, it is possible that you can use register your app through Azure AD and use the generated secrets to configure your app connecting to CRM and do the work that you want. But the office document on Microsoft website is outdated and it took me a couple of days to figure out how to make it work.

The basic process is your app connect to Azure AD and provide all necessary information and in the response it will return a JWT token as well as other information like expiry time. Normally, it is 3600 seconds that is 1 hour. Hence, keep that in mind, you have to renew your token at some point. Alternatively, you can get a new token each time but that’s not an efficient way to do it so.

The organization service, which is based on the SOAP, has been declared deprecated and Microsoft has recommended using the web API for new project. These APIs are all RESTful and you can find the root url from the “Settings” -> “Dev Resurce”.

How to register an app in Azure

Register app

  1. Log into the Azure portal
  2. Find the Azure Active Directory section from the menu bar on the left hand
  3. Select the directory that you want your app access to
  4. Select App Registration
  5. Click the Add button
  6. Enter a unique name
  7. Choose the “Native” option as the Application Type
  8. Enter a redirect URI (for example, http://localhost) and click the creation button

Make a note to the following information:

  • Application ID
  • Redirect URI you entered

Configure Permission

In the Settings page, click the Required Permissions and Add button in the expanded pane.

In the expanded pange, choose the Dynamics CRM online and click the delegated permission. Finish selection and click Done button.

You have finished the app registration in Azure Active Directory

Acquire Token from Azure Active Directory

Microsoft has a page that gives some example codes on how to get a token but as far as I can see, those codes are quite outdated. For example, the AcquireToken method does not exist any more. All of them has been replaced by the asyn method: aAcquireMethodAsync.

I can’t remember how I wrote the code but most of them would be similar to the sample provided by Microsoft team in Github. This page tells you how to acquire token.

The key part is:

AuthenticationResult result = null;
// first, try to get a token silently
try
{
    result = authContext.AcquireTokenSilentAsync(todoListResourceId, clientId).Result;
}
catch (AggregateException exc)
{
    AdalException ex = exc.InnerException as AdalException;

    // There is no token in the cache; prompt the user to sign-in.
    if (ex != null && ex.ErrorCode != "failed_to_acquire_token_silently")
    {
        // An unexpected error occurred.
        ShowError(ex);
        return;
    }
}

if (result == null)
{
    UserCredential uc = TextualPrompt();
    // if you want to use Windows integrated auth, comment the line above and uncomment the one below
    // UserCredential uc = new UserCredential();
    try
    {
        result = authContext.AcquireTokenAsync(todoListResourceId, clientId, uc).Result;
    }
    catch (Exception ee)
    {
        ShowError(ee);
        return;
    }
}

The method: AcquireTokenSilentAsync is used to renew token when you already have the your app running authenticated at startup. The reason why it is called Silent is you don’t need to provide the username and password again as the relevant information is kept in memory.

Note: The first time you run the method AcquireTokenAsync, you will get a consent window where you need to enter your username and password and consent the app is able to do the permission you configured in Azure AD. Once that is done, because I didn’t see any option regard the auth period, I presume it will be forever. You can write a unit to trigger this piece of code so that you don’t need to do it when you put your app into production.

Use the token

Once you get the token, you need to put it into the Authorization header in HTTP headers. For example,

Authorization: Bearer %YOUR_TOKEN%

and other headers as well:

  • Content-type
  • OData-version
  • OData-max-version