Microsoft has started depreciating the Office365 Authentication Type as announced earlier. Microsoft recommends to use OAuth authentication type for CRM connectivity through code. Let’s see how can we do it:
Register an app in Azure Active Directory
Login to Azure Portal and search for Azure Active Directory.
Click on App Registrations.
Click New Registration and Register.
Once Registered, click on Manifest and set the allowPublicClient property to true.
To set Permissions, Click on API Permissions.
Click on Add Permission to add permissions for Dynamics CRM.
Select Access Common Data Service as organization users.
Once permissions are updated, we will see the following.
Next, we will copy the Application (client) ID by clicking on Overview.
Click on Certificates & Secrets and generate the new secret by clicking on New Client Secret.
Copy the newly generated secret for use in our code.
Next step is to create an Application User in CRM.
While creating the Application User, please add the Application ID copied earlier.
Once the user is added, please assign a security role to the user.
Connecting to CRM through code
We will now create a console application in visual studio. Please make sure that .NET Framework is 4.6.2 or later.
Please add the Microsoft.CrmSdk.XrmTooling.CoreAssembly package in your project from NuGet Packages.
In order to use OAuth, the connection string should be in a format as defined here.
In order to verify that we are able to connect successfully to CRM, we will use the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using (CrmServiceClient svcClient = new CrmServiceClient(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString)) { if (!svcClient.IsReady) { Console.WriteLine("unable to connect!"); return; } WhoAmIRequest request = new WhoAmIRequest(); WhoAmIResponse response = (WhoAmIResponse)svcClient.Execute(request); Console.WriteLine("UserId =" + response.UserId.ToString()); } |
Now, you are ready to connect your code to CRM using OAuth. We hope you find this article interesting and helpful.
For questions or insights, leave a comment below or reach out to us at info@optimallogics.com. We are always happy to help.