Server-to-Server (S2S) Authentication with Dynamics 365 – Part 2

Introduction

In Part 2 we will enhance your previously created MVC web application to connect to Microsoft Dynamics 365 and execute basic commands using the Microsoft Dynamics 365 SDK.

Requirements

Web.config

  • Add the following to the appSettings section

Login to Azure AD navigate to App &gtegis<rations select the application you created in Part 1 of this blog. then navigate to Keys.

Copy the newly generated code and past it into the ida:ClientSecret value in your web.config file.

Set Home Controller access as anonymous

  • Navigate to \Controllers\HomeController.cs
  •  Adding the  [AllowAnonymous]  keyword above your action will give the use the ability to access the page anonymously without Authentication.

Create Contact List link 

  • Navigate to ../Views/Shared/_Layout.cshtml and add the following code to display the WhoAmI link on our web application.

We will only display this link if the user has logged in and has been authenticated.

Create CrmController

  • Right click the Controllers folder and select Add > Controller
  • Select MVC 5 Controller – Empty
  • Click Add
  • Add the following properties to the CrmController

  • Create a new method called GetServiceUrl in the CrmController. This method takes the CRM Organisation name and returns the CRM organisations service URL.

  • Add the following code to your Index method

If If you get a error “AuthenticationContext does not contain AcquireToken” make sure that you have added version 2.xx.x of the Microsoft.IdentityModel.Clients.ActiveDirectory assembly reference to your project

Create Crm View

  • Right click the Crm folder and select Add > View…
  • In the Add View dialog, set the following values:

  • Click Add
  • Update your view to represent the following code.

  • Press F5 and test you application.

Source Code