Connection to Dynamics 365 and SharePoint Authentication Using ClientId & ClientSecret: Part 2

, January 12, 2021 336 Views

In our previous post, we saw what needs to be done in Azure and Dynamics 365. Now we will see the code part.

Before we start with coding, the below nuget package should be installed.

Nuget Package: Microsoft.CrmSdk.XrmTooling.CoreAssembly

Reference link: https://www.nuget.org/packages/Microsoft.CrmSdk.XrmTooling.CoreAssembly

For installing the package, open the Visual Studio -> Tools -> NuGet Package Manager -> Manage NuGet Packages for Solutions and install aforesaid nuget package.

Now let us look into the C# code needed to connect with D365. Here we have to create an object of CrmServiceClient that takes the connectionString as a parameter, which is made up of crmOrganizationURL, ClientId and ClientSecret of previously registered application at Azure Active directory. Please find below code for reference:

#region GetOrganizationService

/// <summary>
/// Method to Connect Organization Service using clientID and clientSecret 
/// Returns to IOrganizationService
/// </summary>
public static IOrganizationService GetOrganizationService()
        IOrganizationService organizationService = null;

        string crmOrganizationURL = ConfigurationManager.AppSettings["CRMOrganizationURL"]);//CRM URL:https://inkeysolutionstraining.crm.dynamics.com/ 
        string clientId = ConfigurationManager.AppSettings["ClientId"]);// Client ID: 14b5466b-989e-4536-b7b6-9f0696d115c7
        string clientSecret = ConfigurationManager.AppSettings["ClientSecret"]);// Client Secret: 9655e4c9-afec-4f48-ab26-461220ce2843

        string connectionString = $@"AuthType=ClientSecret;Url={crmOrganizationURL};ClientId={clientId};ClientSecret={clientSecret}";

        // Connecting to Organization Service using crmOrganizationURL, clientId and clientSecret
        var connection = new CrmServiceClient(connectionString);

        if (connection != null &&
            Console.WriteLine("Connected Succesfully.");
            organizationService = connection.OrganizationWebProxyClient != null ? connection.OrganizationWebProxyClient : (IOrganizationService)connection.OrganizationServiceProxy;
            Console.WriteLine("Connection failed");
        return organizationService;
    catch (Exception exception)
        throw exception;


SharePoint Authentication

There are various ways available to connect with SharePoint as below:

  • Using UserName and Password in C# code
  • Using credentials in a secure way (encrypted format)
  • App-only Authentication

Here we will discuss about App-only Authentication.

Create SharePoint App:

App-only Authentication is a model for setting up the app principals. It can be used with SharePoint Online, as well as in SharePoint On-Premise. Below are the steps to be followed to setup the App-only principal.

SharePoint App is created successfully.

Next step is granting permissions to the newly created principal.

We have to create as many numbers of app principals as needed with each app principal having unique permission.

The permission can be any of the below:

  • Read Permission
  • Write Permission
  • Manage Permission
  • FullControl Permission

Along with permission, we can specify the scope. Below are few examples of scope.

  • http://sharepoint/content/sitecollection
  • http://sharepoint/content/sitecollection/web
  • http://sharepoint/content/sitecollection/web/list
  • http://sharepoint/content/tenant

we can use the below code for permission reference.

      <AppPermissionRequest Scope=" http://sharepoint/content/tenant" Right="FullControl"/>  

You can reach this site via(e.g. https:/inkeysolutionstraining-admin.sharepoint.com/_layouts/15/appinv.aspx)

Once the page is loaded add your client id and click on “lookup”. And add permission to “App’s Permission Request XML”.

After that click on “Trust It” button as below:

Implementation of C# Code to connect SharePoint:

Use configuration file to store App Id and App Principals. (e.g. App.config)

Office Dev PnP (Office Developer Patterns and Practices) have https://www.nuget.org/packages/SharePointPnPCoreOnline available to help use app principals in managed C# code.

Below is the managed C# code to connect to SharePoint.

using OfficeDevPnP.Core;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Client;
#region ConnectToSharePoint

    	string sharePointSiteUrl = "https://inkeysolutionstraining.com/sites/demo";// SharePoint URL
    	string clientId = ConfigurationManager.AppSettings["ClientId"]);// Client ID:  27027062-04fb-4818-a928-f14658a9fe90
    	string clientSecret = ConfigurationManager.AppSettings["ClientSecret"]);// Client Secret: UUw3Ci5j/OaKuNytPFxOXzg8bwB+z5FpK9U+qJFn2KY=
       	using (var clientContext = new AuthenticationManager().GetAppOnlyAuthenticatedContext(siteUrl, "Enter ClientId", “Enter ClientSecret"))  
            		clientContext.Load(clientContext.Web, p => p.Title);
            		Console.WriteLine("Connection Succesfully.");
    	catch (Exception exception)
        	Console.WriteLine("Connection failed.");
        	throw exception;


Conclusion :

In this way, we can make use of Client Id and Client Secret to connect with either Dynamics 365 CRM or SharePoint which provides a secure way for authentication.

Hope this blog helps you!!

ATM Inspection PowerApp to ease ATM inspection and report generation process.

Insert data into Many-to-Many relationship in Dynamics CRM very easily & quickly, using the Drag and drop listbox.

Comply your Lead, Contact, and User entities of D365 CRM with GDPR compliance using the GDPR add-on.

Create a personal / system view in Dynamics CRM with all the fields on the form/s which you select for a particular entity using the View Creator.



INKEY is your solution partner.
Our focus is to deliver you in-time intelligent innovative solutions ("key") for the problems in hand. Maintaining a quality standard right from the inception of a project is our top most priority.

Our team of talented professionals will execute your projects with dedication and excellence. We take ownership and accountability for the effort that goes into meeting our client’s needs.

Years of experience and proven success of delivering innovative custom solutions.

More posts by

Leave a Reply

Your email address will not be published. Required fields are marked *