Using .NET Core/MSAL.NET to consume D365 Web API

We can use .NET Core and MSAL.NET library to connect to D365 WebAPI. Following package need to be installed for MSAL.NET library

We are using below configuration for our registered app

Below is the sample code for the getting top 10 accounts. We are using Interactive Mode to get the token :

using Microsoft.Identity.Client;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace D365ConnectionUsingMSAL
{
    class Program
    {
        static async Task Main(string[] args)
        {
            string serviceUri = "https://xxxxxxxx.crm.dynamics.com/";
            string apiVersion = "9.1";
            string crmapiUrl = $"{serviceUri}/api/data/v{apiVersion}/accounts";
            string clientId = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
            string tenantId = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

            var publicClient = PublicClientApplicationBuilder
                .Create(clientId)
                .WithAuthority(new Uri($"https://login.microsoftonline.com/{tenantId}"))
                .WithRedirectUri("http://localhost")
                .Build();

            var scope = new string[] { "https://xxxxxxxxx.crm.dynamics.com/.default" };
            AuthenticationResult result = await publicClient.AcquireTokenInteractive(scope).ExecuteAsync();
            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.Timeout = new TimeSpan(0, 2, 0); 
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
                var data = await httpClient.GetAsync("https://orgb73380c8.crm.dynamics.com/api/data/v9.1/accounts?$select=name,address1_city&$top=10");
                if (data.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    Console.WriteLine(await data.Content.ReadAsStringAsync());
                }
                else
                {
                    Console.WriteLine($"Some thing went wrong : {data.StatusCode} ");
                }
                Console.ReadLine();
            }
        }
    }
}

We can also use below if you have client secret for the registered app.

var confidentialClient = ConfidentialClientApplicationBuilder.Create(clientId: clientId)
.WithClientSecret(secret)
.WithAuthority(new Uri($"https://login.microsoftonline.com/{tenantId}"))
.Build();

%d bloggers like this: