How to establish Server-to-Server Authentication | Dynamics D365 | Azure | CRM Web API

In this blog, I'll explain all steps that how to establish server-to-server authentication using Application User and Azure active directory.

I have a very basic requirement to fetch case guid from incident entity based on ticket number from CRM using S2S authentication i.e without using any CRM user credential. Follow the below steps:

Step 1:First of all we need to create an App in the Azure application directory :
  • Goto http://portal.azure.com and enter your credentials.
  • Goto Active Directory > App Registrations > New Registrations
  • Provide all basic details as in screenshots below and click on Register





  • Once the application is created, you will get an application ID (marked with red arrow in image below), copy and paste somewhere; this is your client ID



  • Next step is to create Client Secret for which click on 'Certificates and Secrets' (or Keys for old Azure UI) as shown in image below. This key is used to establish connection in your application. Click on 'New Client Secret' button



  • Once the client secret is generated, copy and paste it somewhere. (shown in image below). Once you move away from this you'll not be able to read this ID again



  • Next step is to provide permission, click on API Permission and click on 'Add a permission' button (or Required Permission and select Common Data Service for Old Azure)



  • Select 'Dynamics CRM' and then Select 'Delegated permission' as shown in the below images



  • Once done click on Add Permission button at the bottom.



Step 2: Create an 'Application User' in Dynamics CRM. 
  • Goto Settings > Security > Users. Select the 'Application Users' view and click on New



  • Switch form and goto Application user form. Fill all the required details and paste the Application ID which you created during app registration. Don't forget to assign proper role to this user.



Also you'll need token endpoint which you can copy from Azure portal; Goto App Registrations and click on Endpoints, copy OAuth 2.0 token endpoint url.

Step 3: Coding part; Get the Access token and query case record. Install Newtonsoft.Json before starting code

  • Copy and paste below code for getting token:
 public string GetAccessToken()  
     {  
       string jsonResponse;  
       using (var client = new HttpClient())  
       {  
         var request = new FormUrlEncodedContent(new Dictionary<string, string>  
           {  
             {"grant_type","client_credentials"},  
             {"client_id", ClientId},  
             {"client_secret", ClientSecret},  
             {"resource",resource },  
           }  
         );  
         request.Headers.Add("X-PrettyPrint", "1");  
         var response = client.PostAsync(TOKEN_ENDPOINT, request).Result;  
         jsonResponse = response.Content.ReadAsStringAsync().Result;  
       }  
       var values = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonResponse);  
       var AuthToken = values["access_token"];  
       return AuthToken;  
     }  


Note: ClientId, ClientSecret & TOKEN_ENDPOINT variables will have the values which we saved during app registrations, 'resource' variable will have your D365 Url (https://xxxxxxxx.crmX.dynamics.com)

  • Copy and paste below code for fetching case guid based on case number and token.
     public string GetCaseID(string sCaseNumber, string AuthToken)  
     {  
       string CaseId = string.Empty;  
       using (var client = new HttpClient())  
       {  
         client.Timeout = new TimeSpan(0, 2, 0);  
         client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AuthToken);  
         string requestIncident = InstanceUrl + "/incidents" + "?$select=title,incidentid&$filter=title%20eq%20'" + sCaseNumber + "'";  
         var request = new HttpRequestMessage(HttpMethod.Get, requestIncident);  
         request.Headers.Add("Authorization", "Bearer " + AuthToken);  
         request.Headers.Add("OData-MaxVersion", "4.0");  
         client.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");  
         client.DefaultRequestHeaders.Add("OData-Version", "4.0");  
         client.DefaultRequestHeaders.Add("Prefer", "odata.include-annotations=*");  
         request.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));  
         request.Headers.Add("X_prettyPrint", "1");  
         var response = client.SendAsync(request).Result;  
         if (response.StatusCode.ToString() == "OK")  
         {  
           string jsonResponse = response.Content.ReadAsStringAsync().Result;  
           var keyValues = JsonConvert.DeserializeObject<SearchData>(jsonResponse);  
           if (keyValues.value.Count > 0)  
           {  
             CaseId = keyValues.value[0].incidentid;  
           }  
         }  
         else  
           resultJson.Success = "false";  
       }  
       return CaseId;  
     }  

   public class SearchData  
   {  
     public string context;  
     public List<SearchDataValue> value;  
   }  

   public class SearchDataValue  
   {  
     public string incidentid;  
   }  

Comments

  1. Awesome post, thanks Aayush.

    ReplyDelete
  2. Thank you for sharing. We are best crm software company provide all type of crm software for your business. Visit for more information.

    ReplyDelete
  3. He began enjoying in} Zynga Poker, a slot machine game, final 12 months. But he craved the excitement that came with betting real money. Before lengthy, he was inserting bets in a brick-and-mortar on line casino, a lot to his monetary detriment. When he lost greater than $5,000 via a mix of card games and sports betting, he was compelled to ask his parents for money to sort out his debt. That's when he, and his parents, determined he needed to get right into a recovery program. Since 2017, Pennsylvania slots 카지노사이트 sites have begun to appear.

    ReplyDelete

Post a Comment

Popular posts from this blog

Search data in Gridview on Textbox Key press event using JQuery in Asp.Net- C#

StateCode and StatusCode Values for mostly used entities in Microsoft Dynamics CRM 2013

Dumps for Microsoft Dynamics CRM MB2-703 Practice Exam Questions Free

How to import CSV files into DataTable in C#

How to show enlarge image when mouse hover on image or link in Asp.Net(c#) using JavaScript

go to top image