D365 CRM: Use Certificate Thumbprint to connect to D365 CRM API



  • We know that we can use User/Password or App ID/Secret key to connect a D365 Organization CRM API but if you need a high security level of connection, using of a certificate is available. For this you need to configure a valid Certificate in your Azure Tenant where your D365 CRM is installed. 
    You need to run the following Nugets in your project to access the different classes to archive this:

    Install-Package System.Security.Cryptography.X509Certificates
    Install-Package Microsoft.CrmSdk.XrmTooling.CoreAssembly

    The code to connect to a CRM API using thumbprint is the following:

    1.    private CrmServiceClient InitializeOrganizationService()
    2.    {
    3.           // Force TLS 1.2 for Dynamics 365 v9.0 instances
    4.    System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
    5.    string tenantID = “your TENANT ID”;
    6.    string thumbprint = “the THUMBPRINT of your certificate”;
    7.    // Get the Access Token using the thumbprint certificate
    8.    AuthenticationContext authenticationContext = new AuthenticationContext(“https://login.microsoftonline.com/” + tenantID);
    9.    // Find the Certificate by thumbprint in Azure
    10.    X509Certificate2 userCert = FindCertificate(thumbprint, StoreName.My);
    11.     
    12.    var clientCertificate = new ClientAssertionCertificate(clientId, userCert);
    13.     
    14.    AuthenticationResult authenticationResult = authenticationContext.AcquireToken(organizationUrl, clientCertificate);
    15.    string diferencesDate = (authenticationResult.ExpiresOn.Offset.Hours * -1).ToString();
    16.     
    17.    var requestedToken = authenticationResult.AccessToken;
    18.     
    19.    OrganizationWebProxyClient orgWebProxService = new OrganizationWebProxyClient(GetServiceUrl(organizationUrl), false);
    20.     
    21.    orgWebProxService.HeaderToken = requestedToken;
    22.    CrmServiceClient service = new CrmServiceClient(orgWebProxService);
    23.    if (!service.IsReady)
    24.           {
    25.              throw new Exception(service.LastCrmError);
    26.    }
    27.    // Return the Service connected to the CRM Organization
    28.    return service;
    29.    }

    And use this code to find the certificate by thumbprint in your tenant:

    1.    private static X509Certificate2 FindCertificate(string certificateThumbprint, StoreName storeName)
    2.    {
    3.           var storeLocationArray = new[]
    4.           {
    5.               StoreLocation.CurrentUser,
    6.               StoreLocation.LocalMachine
    7.           };
    8.     
    9.          try
    10.          {
    11.             X509Certificate2Collection certificates = null;
    12.             if (storeLocationArray.Any(storeLocation => TryFindCertificatesInStore(certificateThumbprint, storeLocation, storeName, out certificates)))
    13.             {
    14.                 return certificates[0];
    15.             }
    16.          }
    17.          catch (Exception ex)
    18.          {
    19.             throw new Exception(string.Format("Failed to find certificate with thumbprint: {0}.", certificateThumbprint), ex);
    20.          }
    21.     
    22.          throw new Exception(string.Format("Failed to find certificate with thumbprint: {0}.", certificateThumbprint));
    23.    }
    24.     
    25.    private static bool TryFindCertificatesInStore(string thumbprint, StoreLocation location, StoreName storeName, out X509Certificate2Collection certificates)
    26.    {
    27.          X509Store store = new X509Store(storeName, location);
    28.          store.Open(OpenFlags.ReadOnly);
    29.          certificates = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);
    30.          store.Close();
    31.     
    32.          return certificates.Count > 0;
    33.    }

    Enjoy it!






  • Comments



Add a Comment