Authentication between Dynamics 365 Web Api and external web application without user prompt

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
As promised, I am back to my second post on this topic. In my previous post, I showed you on how to generate Authorization token of D365 online from Native Console App using the Client_ID.
https://debajmecrm.com/headless-authentication-with-dynamics-crm-online-web-api-without-user-login-screen-without-using-adal-part-i/


We did that using simple HttpWebRequest and Response and did not use the ADAL (Active directory authentication library) as well.
Well, let’s dive deep here. Nothing big in my previous topic as the same thing can be done using ADAL and in a clean way as well. Then why use that construct?
We are talking of headless authentication here which means authentication without user intervention. Using ADAL, it was fine to generate the token from a Native console APP using the Client ID. However situations become complex when we try to do the same from an external Web Application which required the Client_Secret as well for generating the token.
So I created a ASP.NET web application and registered in Azure. I got the client id and client secret after registering the Web App. How to do that? Well you have many wonderful blogs out there and I am not going to repeat the same.
Now comes the code part. Below is the code for the same. Look at highlighted line to check how I am passing the client id and client secret
My CRM URL is – https://xrm4u1.crm.dynamics.com

public string GetCRMToken()
{
var azureTenantId= “xrm4u1.onmicrosoft.com”;
var clientId = “<client id of the Web app after registering in azure>”;
var clientSecret = “<client secret of the Web 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}&client_secret={1}&resource={2}&username={3}&password={4}&grant_type=password”,
clientId, clientSecret,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;
        }

And delight is when you get the access token back. Now with the access token in your hand, you have the trump card. You can query Web API and what not.
Great isn’t it? To be honest with my readers, after this method without using ADAL worked out in my previous post, I just tried out sending the client secret in exactly the same way and it worked like a charm. Serendipity you can say!
Hope this helps.
Debajit Dutta
(Dynamics MVP)
For corporate training/ consulting please write to us at info@xrmforyou.com


Discover more from Debajit's Power Apps & Dynamics 365 Blog

Subscribe to get the latest posts sent to your email.

1 thought on “Authentication between Dynamics 365 Web Api and external web application without user prompt”

Comments are closed.

Discover more from Debajit's Power Apps & Dynamics 365 Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading