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.
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 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())
clientId, clientSecret,url, userName, password);
var postBytes = Encoding.ASCII.GetBytes(postData);
reqStream.Write(postBytes, 0, postBytes.Length);
var accessToken = default(string);
using (var response = (HttpWebResponse)request.GetResponse())
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.
For corporate training/ consulting please write to us at email@example.com
Published at Mon, 30 Apr 2018 08:41:46 +0000