Consume External Web Api authenticated with Azure ADAL from CRM Online Plugin
Hi folks, In my previous post i explained about Creating Sample Web Api and Host in Azure with ADAL
In this blog i will demonstrate step by step on how to authenticate and consume data from External Web API hosted in Azure with ADAL.
Before Accessing Azure Hosted Web Api ,we have to get the Unique Identifiers details which i explained in my previous blog.
- Application Id
- Client Secret Key
- OAuth 2.0 Token Endpoint
- OAuth 2.0 Authorization Endpoint
Retrieve Application Id:
Open portal.azure.com.
If you have read my previous blog Create Sample Web API and Deploy it in Azure with ADAL You may be aware that i have created two Apps in AAD(Parent and Client).
- Navigate to Azure Active Directory-> App Registration
- Open the Parent App Created, In view you can see the Application Id(i.e Client Id)
Retrieve Client Secret Key;
- If you read my previous Blog i have shown how to create Client Secret Key Step 8 & Step 9
OAuth 2.0 Token Endpoint:
Navigate to Azure Active Directory -> App Registration -> End Points -> OAuth TokenEndPoint as shown below
OAuth 2.0 Authorization Endpoint:
Follow same as shown in previous step
Now let us dig into CRM Online plugin
Step 1: Create plugin and add the required references.
For authenticating External Web API hosted in Azure ADAL, first we need to generate token as Azure which uses OAuth 2.0 in Web API Management.
Note: Without token we can't connect to external web api
ApplicationId = Client Application Id;
ClientSecret = Client Secret Key Click Here as shown in step 8 & 9Authority = "https://login.microsoftonline.com/{tenant-id}/oauth2/authorize?resource={ApplicationId}";
Below code uses ADAL .Net Library to retrieve Azure Token.
await authContext.AcquireTokenAsync("{Parent-Application Id}",Credentials);
Now we got the required token in the AuthenticationResult.
Note: If we use the above code and merge dll using ILMerge and register it in Dynamics CRM Online (Sandbox mode) it will work perfectly, But when you move to Full-Trust Mode it will throw below shown error
Step 2: To Eliminate this Issue We have to use HTTPClient POST Request to OAuth 2.0 Token Endpoint as shown below.
Create an Model for assigning response values from HTTPClient
Create and assign below mentioned variables.
clientApplicationId
: Client App Id
clientClientSecret
: Client App's Secret Key
ParentAppApplicationId
: Parent AppId Click Here as shown in step 8 & 9
Copy the below given code which will retieve Azure token using HTTPClient
[sourcecode language="C#"]
string clientApplicationId = "00000000-0000-0000-000000000000";
string clientClientSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string ParentAppApplicationId = "00000000-0000-0000-000000000000";
string tenandId = "00000000-0000-0000-000000000000";
string oauthUrl = string.Format("https://login.microsoftonline.com/{0}/oauth2/token", tenandId);
string reqBody = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&resource={2}", Uri.EscapeDataString(clientApplicationId), Uri.EscapeDataString(clientClientSecret), Uri.EscapeDataString(ParentAppApplicationId));
HttpClient client = new HttpClient();
HttpContent content = new StringContent(reqBody);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
using (HttpResponseMessage response = await client.PostAsync(oauthUrl, content))
{
if (response.IsSuccessStatusCode)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AzureAccessToken));
Stream json = await response.Content.ReadAsStreamAsync();
AzureAccessToken token = (AzureAccessToken)serializer.ReadObject(json);
}
}
[/sourcecode]
Step 3: Code for Getting Response from External Web API:
Use HTTPWeb Request instead of ADAL .Net Library to get the response from External Web API as shown below
Now if we register in either SandBox or Full-Trust Mode Plugin code will works like a charm.
Hope it's Helpful !!!!! Happy Coding #Herbi_Coder
*This post is locked for comments