User Review
( vote)Sharing a sample code to consume Dynamics 365 Web API using MSAL.NET
Create a console application and add the following NuGet Package
- Microsoft.Identity.Client
More on Microsoft identity platform
https://docs.microsoft.com/en-us/azure/active-directory/develop/
We are using ConfidentialClientApplicationBuilder create method.
The sample code –
using Microsoft.Identity.Client; using System; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; namespace CrmAppMSAL { class Program { static async Task Main(string[] args) { string clientId = "fc34502a-74db-4977-8c83-***********"; string secret = "5~mByJeQ8dDO2LZP_H_J2**********"; string[] scope = new string[] { "https://orgname.crm15.dynamics.com/.default" }; string webAPI = "https://[org].crm15.dynamics.com//api/data/v9.0/leads"; string authority = "https://login.microsoftonline.com/7bc93881-0733-48ab-baa1-ee3ed7717633"; var clientApp = ConfidentialClientApplicationBuilder.Create(clientId: clientId) .WithClientSecret(clientSecret: secret) .WithAuthority(new Uri(authority)) .Build(); try { AuthenticationResult authResult = await clientApp.AcquireTokenForClient(scope).ExecuteAsync(); var httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0"); httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0"); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken); httpClient.BaseAddress = new Uri(webAPI); var response = httpClient.GetAsync("WhoAmI").Result; if (response.IsSuccessStatusCode) { var userDetails = response.Content.ReadAsStringAsync().Result; Console.WriteLine(userDetails); Console.WriteLine(authResult.AccessToken); Console.WriteLine(authResult.ExpiresOn); Console.ReadLine(); } } catch (Exception ex) { string errorMessage = ex.Message; } } } }
Result –
Reference –
https://medium.com/capgemini-microsoft-team/access-tokens-for-dynamics-365-using-microsoft-authentication-library-2b16c9f794b
Hope it helps..