In this blog post, I’m going to explain how to connect to Dynamics 365 Online from a C# Console App, Azure Function, or any other external application. I’ll be showing how to connect using an Azure App registration. This approach uses a Client ID and Client Secret, in addition to Server URL, instead of your typical Username and Password.
Using an app registration allows us to get around MFA and password expiry restrictions that are becoming more standard across businesses, which makes connecting with Username and Password increasingly more difficult.
If you do still want/need to use Username and Password, I’ll be explaining how you can still do that in another blog post.
First of all, make sure your project has the latest Microsoft.CrmSdk.XrmTooling.CoreAssembly nuget package. The latest version (9.1.x.x) includes important updates that allow these connections to work a lot easier than in previous versions.
You can set up an Azure App Registration and connect it with your Dynamics 365 organisation to a new App User giving system admin or whatever it needs, and you don’t have to worry about MFA or passwords expiring.
Setting this up is straight forward, although there are a few steps involved.
Now that Azure is all good to go, we need to create a new App User in Dynamics 365 using the new App registration.
Now you should have the following 3 things needed to authenticate with the Dynamics 365 SDK:
From your code, you can now simply connect to the CrmServiceClient using the following constructor:
string serverUrl = "https://org.crm6.dynamics.com"; string clientId = "3766f0db-3434-457f-8742-8607946814ad"; string clientSecret = "VwW1=3UZnFA=x?@J3kR9IZB1MCMMqz69"; // This should be encrypted CrmServiceClient sdk = new CrmServiceClient(new Uri(serverUrl), clientId, clientSecret, false, ""); if (sdk != null && sdk.IsReady) { sdk.Execute(new WhoAmIRequest()); }
Note: If the constructor above doesn’t exist for you, make sure to update the XrmTooling nuget package to the latest 9.1.x.x.
That’s all there is to it, now you can run services and applications as this app user without ever worrying about passwords expiring or multi-factor authentication restrictions getting in the way.
You can also reuse the Azure app registration (Client ID and Secret) across other Dynamics 365 environments within your tenant, which makes it easy to connect to your various environments if you need to switch between them while debugging etc. Just create the App User in each environment using the same Application ID.
This is definitely my preferred approach when it comes to connecting to Dynamics 365 now. It’s simple enough to set up, and you don’t have to worry about Office 365 policies on users. If for whatever reason you do still need to use Username and Password, I’ll be writing a follow-up blog post which covers a couple of different ways you can still do this.