Headless Authentication with Dynamics CRM online Web API – Without using Active Directory Authentication Library (ADAL) {Part-I}

Follow my blog for more interesting topics on Dynamics 365, Portals and Power Platform. For training and consulting, write to us at info@xrmforyou.com
Well this topic has been discussed again over multiple times. And I myself has written a blog on how to do a headless authentication (without user intervention) between Dynamics CRM Online Web API and Native APP (console APP) – https://debajmecrm.com/dynamics-crm-web-api-login-authentication-screen/
If you go through the above post, I have used ADAL (active directory authentication library) to query the authorization token and then use the authorization token to query the Dynamics CRM Web API. However there is a catch to this.
This headless authentication was only possible with Native APPs (console APPs) since they just required Client ID’s and does not require the Client Secret to actually generate the token. And hence I was not able to use this method to get the token from a Web Application which would require the Client_Secret.
And while I was doing a training session on this recently, I was asked the question. Is there really no way? Is ADAL absolutely necessary?
Well that sparked me. I decided to spend some time and dig deep. I tried to extend the AcquireToken method of ADAL but to no use. A lot of digging and finally came up with this.
This is Part-I of this blog. Here I will first show you how to get the token from D365 online from a Native App like C# console APP. In the next blog I will show you how we can extend this to use for client_secret as well.
My CRM URL – https://xrm4u1.crm.dynamics.com
I am not going into detail on how to register an APP in azure and give it access to Dynamics CRM. There are so many wonderful blogs which explains in detail. Below is the code to just obtain the token with using any external libraries (ADAL or anything)
public string GetCRMToken()
{

var azureTenantId= “xrm4u1.onmicrosoft.com”;
var clientId = “<client id of the console app after registering in azure>”;
var requestUrl = string.Format(@”
https://login.microsoftonline.com/{0}/oauth2/token”,
azureTenantId);

var url = “https://xrm4u1.crm.dynamics.com”;
            var userName = “<username>”;
var password = “<password>”;

            // Connect to the authentication server
            var request = (HttpWebRequest)WebRequest.Create(requestUrl);
request.Method = “POST”;


            using (var reqStream = request.GetRequestStream())
{
var postData = string.Format(@”client_id={0}&resource={1}&username={2}&password={3}&grant_type=password”,
clientId, url, userName, password);
var postBytes = Encoding.ASCII.GetBytes(postData);
reqStream.Write(postBytes, 0, postBytes.Length);
reqStream.Close();
}

            var accessToken = default(string);
using (var response = (HttpWebResponse)request.GetResponse())
{

var stream= response.GetResponseStream();
if (stream!= null)
{
var reader = new StreamReader(stream);
var json = reader.ReadToEnd();

              // Here I am using Newtonsoft.json

                    var dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
accessToken = (string)dict[“access_token”];

                  
                }
}

            return accessToken;
        }
Smooth isn’t it? No reference to ADAL. Just simple HttpWebRequest and response.
Hope you liked this.
In the next blog I will show you how to extend this to even include client secret and get the token even from a Web application, which so many has been longing for sometime now.
Debajit Dutta
(Dynamics MVP)
For corporate training/ consulting please write to us at info@xrmforyou.com

1 thought on “Headless Authentication with Dynamics CRM online Web API – Without using Active Directory Authentication Library (ADAL) {Part-I}”

Comments are closed.