After depecation announcemnt of Dynamics 2011 Organization Service Endpoint in late 2018 and recommendation on using OAuth authentication & Dynamics 365 WebAPI, there was uncertainity for developers who were using/planning to use 3rd party integartion using C# SDK.
Ref: https://crmtipoftheday.com/1155/the-clock-is-ticking-on-your-endpoint/
Finally, CrmServiceClient
provides option to connect to organization service using Client Id & Client Secret. Let’s try it out.
Why to use Client ID & Client Secret to Authenticate
- Only minor code chanegs required in existing code.
- OAuth is safer than using password based authenticaton.
- Save user licencing cost by using Application User
Sample Code
As part of initial setup Application User & Azure AD App is required if you don’t have it already please refer to Step 1 & Step 2 in this artice. Once you have all the details, prepare connection string as shown below and use AuthType=ClientSecret here.
public static IOrganizationService GetOrganizationServiceClientSecret(string clientId, string clientSecret, string organizationUri)
{
try
{
var conn = new CrmServiceClient($@"AuthType=ClientSecret;url={organizationUri};ClientId={clientId};ClientSecret={clientSecret}");
return conn.OrganizationWebProxyClient != null ? conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;
}
catch (Exception ex)
{
Console.WriteLine("Error while connecting to CRM " + ex.Message);
Console.ReadKey();
return null;
}
}
IOrganizationService orgService = GetOrganizationServiceClientSecret(
"<Client Id obtained from Azure AD App>",
"<Client Secret obtained from Azure AD App>",
"<Organization Uri>");
var response = orgService.Execute(new WhoAmIRequest());
All the necessary packages should be installed, package Microsoft.CrmSdk.XrmTooling.CoreAssembly version should be 9.1.0.13 or higher in order to connect using ClientSecret. see release notes.
You can find this code on my GitHub.
Feel free to get back in case of any suggestions/queries.