Skip to main content

Notifications

Announcements

No record found.

Use CRM Web API in C# in Dynamics 365 using Azure Authentication

Login to Azure Portal using URL http://portal.azure.com/

Use Credentials for your Dynamics 365 Account and you will land on the page like this. Click the Azure service icon “Azure Active Directory” here.

Then click on “App registration” option from left panel

Then on next screen, if you do not have any app registered here already then click “New Registration” option, otherwise click on link of your App under “Owned applications”, shown in this screenshot as 1 and 2, respectively.

When you clicked “New registration”, following screen will be in front of you and just fill this and hit the “Register” button.

Now your App is registered successfully and some useful IDs are created which we will use in a C# console application to perform Azure AD Authentication to get access token which will be used to retrieve data from CRM application. Next, click on “Certificates and secrets” option from left panel to generate Client Secret.

In next page you need to click on “New client secret” option

Then a record for client secret will be created successfully. You need to just copy the generated client secret and save that in some notepad to use that in C# console application for retrieval of data from CRM.

Now just go to home page in your Azure portal and copy the Tenant ID as shown in this screenshot

Now you have four things which are needed to authenticate your CRM Web API requests using Azure AD in C# i.e.

  1. ClientId
  2. ClientSecret
  3. TenantId
  4. CRM environment base URL

Next, you can see a C# code snippet to get Access token using OAuth2 from Azure AD of your Dynamics 365.

Complete code with an API call and Access token is given below. Please note that the code has dummy ClientId, ClientSecret, TenantId and CRM environment base URL. Please create these IDs with your own Dynamics 365 credentials and this C# code will work without any issue.

using System;
using System.Net;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Threading.Tasks;
using System.Net.Http.Headers;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

namespace CRMConnectAzure
{
    class Program
    {
        private const string ClientId = "7a58c565-6748-42a2-5555-abcd9f2e18e3";
        
        //Azure Application Client Key / Secret
        private const string ClientSecret = "m.99KxU-PBh-S4NEUBnNbaRRat.MG7_n04";

        private const string TenantId = "7ffd1e73-c19f-8685-b4cf-46302a8fca78";

        //Resource / CRM Url
        private const string CrmURL = "https://mytechsolutions1.crm4.dynamics.com";

        //Guid is your Azure Active Directory Tenant Id
        
        private const string Authority = "https://login.microsoftonline.com/"+ TenantId +"/oauth2/token";

        private static AuthenticationResult _authResult;

        static void Main(string[] args)
        {
            AuthenticationContext authContext = new AuthenticationContext(Authority);
            ClientCredential credentials = new ClientCredential(ClientId, ClientSecret);
            _authResult = authContext.AcquireToken(CrmURL, credentials);
            Task.WaitAll(Task.Run(async () => await GetAccounts()));
            Console.ReadLine();
        }

        private static async Task GetAccounts()
        {
            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.BaseAddress = new Uri(CrmURL);
                httpClient.Timeout = new TimeSpan(0, 2, 0);
                httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
                httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _authResult.AccessToken);
                //Add this line for TLS complaience
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
                var retrieveResponseTest = httpClient.GetAsync("/api/data/v9.1/accounts?$select=accountid,name,_primarycontactid_value&$filter=name ne null&$top=15").Result;
                if (retrieveResponseTest.IsSuccessStatusCode)
                {
                    var jRetrieveResponse = JObject.Parse(retrieveResponseTest.Content.ReadAsStringAsync().Result);
                    dynamic collAccounts = JsonConvert.DeserializeObject(jRetrieveResponse.ToString());
                    foreach (var data in collAccounts.value)
                    {
                        Console.WriteLine("Account Name – " + data.name.Value + " - Guid: " + data.accountid.Value);
                    }
                }
                else
                {
                    return;
                }                    
            }
        }
    }
}

Thats it!

Comments

*This post is locked for comments