Aug 29, 2019

Connect to WebApi using ClientId and Secret

We can now register our Dynamics 365 CE in Azure Active Directory, so that platform can be accessed through different client applications using OAuth. Idea behind is client applications can securely access WebApi using just Client Id and Secret.

Below is a code snippet with C# in .NET Framework 4.6.2 to achieve it.

Click here to see how to register D365 CE in Azure

Only two NuGet packages required. (Please note one of them are not in latest version)


using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Clients.ActiveDirectory;


namespace ConnectWebApiWithClientId
{
    class Program
    {
        static void Main(string[] args)
        {
            Task.WaitAll(Task.Run(async () => await Auth()));
        }

        public static async Task Auth()
        {
            string url = "https://SumeTest.crm.dynamics.com";
            string clientId = "5d83f9es-a577-4s01-ab9b-9513e39k970c";
            string secret = "MvrHJ2T2YK7NabYFRSOfrEqLMME/1OMW8n6sVBA7zxI=";
            string apiVersion = "9.1";

            try
            {
                var userCredential = new ClientCredential(clientId, secret);
                string webApiUrl = $"{url}/api/data/v{apiVersion}/";

                var authParameters = AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(webApiUrl)).Result;

                var authContext = new AuthenticationContext(authParameters.Authority, false);
                var authResult = await authContext.AcquireTokenAsync(url, userCredential);
                var authHeader = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);

                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri(webApiUrl);
                    client.DefaultRequestHeaders.Authorization = authHeader;

                    // Use the WhoAmI function
                    var response = client.GetAsync("WhoAmI").Result;
                    if (response.IsSuccessStatusCode)
                    {
                        Console.WriteLine("Authenticated Successfully");
                        Console.WriteLine("Environement : {0}", url);
                        Console.WriteLine();
                    }
                    else
                    {
                        Console.WriteLine("The request failed with a status of '{0}'", response.ReasonPhrase);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex.InnerException;
            }
            Console.WriteLine("Click Enter to Exit Application");
            Console.ReadLine();
        }
    }
}

Hope this helps.

No comments:

Post a Comment