Authenticate Bot with Dynamics 365

Dynamics 365 enables secure and seamless connection with the external applications and services using Server to Server Authentication (S2S) and this is infact the approach that the apps deployed in the Microsoft AppSource use to access Dynamics 365 resources. This documentation dives deeper on this topic.
There are numerous blogs that explain how we can acquire the token leveraging the S2S authentication and here is one.

Let’s quickly review the key points laid out in the blog (provided above):

  1. Register an Active Directory application in order to obtain the Client ID, Client Secret and add API Permission for Dynamics CRM.
  2. Setup an Application User with the Client ID obtained from the 1st step above and provide it with a Security Role that makes sense.
  3. Use the Client ID, Client Secret, Authority and Resource in order to acquire the token, which will be used to access Dynamics 365.

In a third party web application, this is something you would do if you want to access the Dynamics 365 with a specific user (let’s call it application user) to access the Dynamics 365 resources. This definitely has a place in a lot of scenarios where you would want an Application User (in other words, System User) to take care of the backend resource access without consuming any license and this authentication flow enables a few benefits as well.

But there is a business case for another authentication flow where we do not let the System User access the D365 resources, rather we let the real human agents to authenticate themselves and access the D365 resources controlled by their own access like a real OAuth style (not that the other authentication flow is not a real OAuth style) that we are all familiar with most of the commercial applications – sort of B2E authentication. This enables the agents to perform actions like creating the case, finding the cases assigned to them, finding their activities etc.,
Good news is that the Bot framework has something up in its sleeve that will allow us to implement this very easily.

The end result is that the Dynamics 365 user will be able to to authenticate himself directly from within the bot while he/she engages in the conversation.

Let’s see how we can implement this step by step – once you have completed the step 1 (registering an AD application) mentioned above.

  1. Open up the application that you registered in the Active Directory and click on Authentication. Under Redirect URIs, add a new Redirect URI as shown below.

2. Open the WebApp Bot in Azure in click on Settings. Navigate to the section OAuth Connection Settings and click on Add Setting.

With the WebApp Bot, we have a section called OAuth Connection Settings. This allows us to setup a new Connection within the OAuth Connection Setting.

3. I am naming this as “Dynamics Authentication v2”, but you are free to provide whatever name that makes sense to you. Make a note of this Connection Name as we will need in the below step.

  • Choose the Service Provider as Dynamics CRM Online. Copy the Client id and Client secret from the application that you had registered in Active Directory.
  • Enter the Tenant ID of your Dynamics 365’s tenant.
  • Set the Grant Type as user_impersonation
  • For Resource URL , Full Discovery URL, provide your Dynamics 365 URL.
  • Click on Save.

4. You can also choose to click on the Test Connection, and as it implies will test the connection with the given credentials and obtain a token.

5. Download the Bot Authentication project sample code from the Bot builder sample and open it.

6. In the AuthenticationBot.cs file, provide the Connection Name of the OAuth Connection Setting that you just created.

7. In the file, ensure that the appId and appPassword is set. These can be obtained from your Azure Web App Bot’s Configuration section.

8. Run the application and launch the bot in the Emulator and type something and you should see a Sign In button. This is nothing but the OAuthCard of the bot framework. This card is backed by a Dialog which will take the user through the authentication process and finally returns the token.

Here is the OAuthPrompt code that makes this happen.

9. Click on the Sign In and you will be navigated to login to the Dynamics 365 on a popup.

10. The first time, as expected, we will be presented with the Consent screen.

11. Once logged in, you will be redirected to the emulator with the below message.

12. And when you click on “Yes”, you should see the Token from the provider, which you can use to access Dynamics 365 with the below code.

using(var httpClient = new HttpClient())
// Set headers
httpClient.Timeout = new TimeSpan(0, 2, 0); // 2 minutes
httpClient.BaseAddress = new Uri(_serviceUrl);
httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
new MediaTypeWithQualityHeaderValue("application/json"));
// Use the bearer token here
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResponse.Token);
HttpResponseMessage whoAmIResponse = await httpClient.GetAsync("api/data/v9.1/WhoAmI()");
Guid userId;
if (whoAmIResponse.IsSuccessStatusCode)
var jWhoAmIResponse = JObject.Parse(whoAmIResponse.Content.ReadAsStringAsync().Result);
// Finally, Get the userId
userId = (Guid)jWhoAmIResponse["UserId"];

That’s it. You have successfully acquired the token in order to access Dynamics 365 resources. This opens a lot of possibilities with accessing the Dynamics 365 as the bot essentially can access the Dynamics 365 as the user who is logged in with the same Security Role privilege. In a future blog, I’ll explore how we can use this token to create a simple case management application with the Dynamics 365.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s