Accessing Microsoft Dynamics CRM Web APIs Using Self-Hosted WCF Services

You must be wondering why you would use ‘self-hosted’ WCF services when you can host WCF Service on IIS.

Well, I was lucky enough to access CRM Web APIs using a native client application like a console application. But unfortunately, I was not able to get it working from my web application. A web application requires us to use the client secret and client ID (both can be obtained once you register your application in Azure AD) to retrieve an access token. To achieve this, I could not find an overload method to acquire the token.

The following post lists down the limitations and describes why it is not working for my web application although it works for a console application.

http://www.cloudidentity.com/blog/2014/07/08/using-adal-net-to-authenticate-users-via-usernamepassword/

Hence my solution was to host my WCF code inside a native console application, i.e. a self-hosted WCF Service. I registered the console application which hosts the WCF Services in Azure AD and everything is working fine.

The below code is of my native C# console application.

Note that I used the following NuGet packages.

  • Clients.ActiveDirectory: Contains binaries of the Active Directory Authentication Library (ADAL)
  • JSON 
  1. using Microsoft.IdentityModel.Clients.ActiveDirectory;  
  2. using Newtonsoft.Json;  
  3. using Newtonsoft.Json.Linq;  
  4. using System;  
  5. using System.Web;  
  6. using System.Collections.Generic;  
  7. using System.Linq;  
  8. using System.Net;  
  9. using System.Net.Http;  
  10. using System.Net.Http.Headers;  
  11. using System.Text;  
  12. using System.Threading.Tasks;  
  13. using System.ServiceModel;  
  14. using System.ServiceModel.Description;  
  15. using System.ServiceModel.Web;  
  16. using System.Runtime.Serialization;  
  17. using System.IO;  
  18. using System.Xml;  
  19. using System.Reflection;  
  20.   
  21. namespace CRMTest  
  22. {  
  23.     class Program  
  24.     {  
  25.         [ServiceContract]  
  26.         public interface IDynCRMProxyService  
  27.         {  
  28.             [OperationContract]  
  29.             [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json,  
  30.             UriTemplate = "/getAccountInfo")]  
  31.             Account LoadAccounts();  
  32.         }  
  33.   
  34.         public class DynCRMProxyService : IDynCRMProxyService  
  35.         {  
  36.             public Account LoadAccounts()  
  37.             {  
  38.                 string token = getAccessToken();  
  39.   
  40.                 var webRequest = (HttpWebRequest)WebRequest.Create(new Uri(  
  41.                     "https://ur-crm.api.crm5.dynamics.com/api/data/v8.1/accounts?$top=1"));  
  42.                 webRequest.Method = "GET";  
  43.                 webRequest.ContentLength = 0;  
  44.                 webRequest.Headers.Add("Authorization", String.Format("Bearer {0}", token));  
  45.                 webRequest.Headers.Add("OData-MaxVersion""4.0");  
  46.                 webRequest.Headers.Add("OData-Version""4.0");  
  47.                 webRequest.ContentType = "application/json; charset=utf-8";  
  48.   
  49.                 Account account = new Account();  
  50.   
  51.                 using (var response = webRequest.GetResponse() as System.Net.HttpWebResponse)  
  52.                 {  
  53.                     using (var reader = new System.IO.StreamReader(response.GetResponseStream()))  
  54.                     {  
  55.                         string responseContent = reader.ReadToEnd();  
  56.                         dynamic dynamicObj = JsonConvert.DeserializeObject(responseContent);  
  57.                         foreach (var data in dynamicObj.value)  
  58.                         {  
  59.                             account.name = data.name.Value;  
  60.                         }  
  61.                     }  
  62.                 }  
  63.   
  64.                 return account;  
  65.             }  
  66.         }  
  67.   
  68.         public static string getAccessToken()  
  69.         {  
  70.             string username = ConfigurationManager.AppSettings["username"];  
  71.             string password = ConfigurationManager.AppSettings["password"];  
  72.             string authorityUriString = ConfigurationManager.AppSettings["authorityUri"];  
  73.             string domain = ConfigurationManager.AppSettings["domain"];  
  74.             string clientId = ConfigurationManager.AppSettings["clientId"];  
  75.   
  76.             UserCredential userCredential = new UserCredential(username, password);  
  77.             string authorityUri = authorityUriString;  
  78.             AuthenticationContext context = new AuthenticationContext(authorityUri);  
  79.             AuthenticationResult result = context.AcquireToken(domain, clientId, userCredential);  
  80.   
  81.             return result.AccessToken;  
  82.         }  
  83.   
  84.         static void Main(string[] args)  
  85.         {  
  86.             Uri baseAddress = new Uri("http://localhost:58535/hello");  
  87.   
  88.             using (ServiceHost host = new ServiceHost(typeof(DynCRMProxyService), baseAddress))  
  89.             {  
  90.                 host.Open();  
  91.   
  92.                 Console.WriteLine("Service is up at {0}", baseAddress);  
  93.                 Console.WriteLine("Press enter to stop service.");  
  94.                 Console.ReadLine();  
  95.   
  96.                 host.Close();  
  97.             }  
  98.         }  
  99.     }  
  100. }   

Following information has been stored in the config file of the console application.

  1. <appSettings>  
  2.   <add key="username" value="[email protected]"/>  
  3.   <add key="password" value="password"/>  
  4.   <add key="authorityUri" value="https://login.windows.net/ur-crm.onmicrosoft.com/oauth2/authorize"/>  
  5.   <add key="domain" value="https://ur-crm.crm5.dynamics.com"/>  
  6.   <add key="clientId" value="clientId"/>  
  7.   <add key="apiUrl" value="https://ur-crm.api.crm5.dynamics.com/api/data/v8.1/"/>  
  8. </appSettings>   

authorityUri is Azure AD’s OAUTH 2.0 Authorization Endpoint.

clientId is the application ID that you get when you register your application with Azure Active Directory. You need to register this console application in Azure AD to allow access to CRM Web APIs.

Let’s see the steps of registering a console application in Azure AD.

  1. Login to portal.azure.com.
  2. Go to App registrations.
  3. Add the new application as seen below, make sure to select Application Type as ‘Native’.


  4. In settings, you will be able to retrieve the Application ID. Copy it as this will be used as the clientId in the code.

  5. Thereafter, we need to give required permissions for our application. Go to settings -> Required Permissions and grant ‘Delegated Permissions’ to CRM online as seen below.


    Run your console application and a WCF client will be able to consume WCF services which retrieves the CRM data.

Up Next
    Ebook Download
    View all
    Learn
    View all