private async Task<AuthenticationResult> AuthenticateAsync() { AuthConfig config = AuthConfig.ReadJsonFromFile("appsettings.json"); IConfidentialClientApplication app; app = ConfidentialClientApplicationBuilder.Create(config.ClientId) .WithClientSecret(config.ClientSecret) .WithAuthority(new Uri(config.Authority)) .Build(); string[] ResourceId = new string[] { config.ResourceId }; AuthenticationResult result = null; return result = await app.AcquireTokenForClient(ResourceId).ExecuteAsync(); }
private static async Task RunAsync() { AuthConfig config = AuthConfig.ReadJsonFromFile("appsettings.json"); IConfidentialClientApplication app; app = ConfidentialClientApplicationBuilder.Create(config.ClientId) .WithClientSecret(config.ClientSecret) .WithAuthority(new Uri(config.Authority)) .Build(); string[] ResourceId = new string[] { config.ResourceId }; AuthenticationResult result = null; try { result = await app.AcquireTokenForClient(ResourceId).ExecuteAsync(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Token acquired \n"); Console.WriteLine(result.AccessToken); Console.ResetColor(); } catch (MsalClientException ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(ex.Message); Console.ResetColor(); } if (!string.IsNullOrEmpty(result.AccessToken)) { var httpClient = new HttpClient(); var defaultRequestHeaders = httpClient.DefaultRequestHeaders; if (defaultRequestHeaders.Accept == null || !defaultRequestHeaders.Accept.Any(h => h.MediaType == "application/json")) { httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); } defaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", result.AccessToken); HttpResponseMessage responseMessage = await httpClient.GetAsync(config.BaseAddress); if (responseMessage.IsSuccessStatusCode) { Console.ForegroundColor = ConsoleColor.Green; string jsonResponse = await responseMessage.Content.ReadAsStringAsync(); Console.WriteLine(jsonResponse); } else { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"Failed to call Web API: {responseMessage.StatusCode}"); string jsonResponse = await responseMessage.Content.ReadAsStringAsync(); Console.WriteLine($"Content: {jsonResponse}"); } Console.ResetColor(); } }