Advertisements

Headless Authentication with Dynamics CRM online and External Web App which requires Client Secret

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/2018/04/29/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

Advertisements

About Debajit
I am a Dynamics CRM Most Valuable Professional (MVP) with 10 years of experience in Microsoft .NET Technologies and 7 years of dedicated experience in Microsoft Dynamics CRM. I have worked with companies like Microsoft, SanDisk, PwC, TMF Group and have extensive experience of implementing complex CRM solutions from both offshore and client side. Currently the face of XrmForYou.com with significant experience in delivering corporate training on Dynamics CRM and have already delivered multiple projects to client through XrmForYou.com Author of multiple tools on codeplex including the 'Role Based Views' and 'CRM-Sharepoint Metadata manager & Attachment Extractor' which are available for commercial use under XrmForYou.com For consulting/ training, drop me a note at info@xrmforyou.com or visit our website www.xrmforyou.com

One Response to Headless Authentication with Dynamics CRM online and External Web App which requires Client Secret

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: