Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 2 Current »

The following was written using .NET Core 3.1

Packages

  1. https://www.nuget.org/packages/Microsoft.Identity.Client
  2. https://www.nuget.org/packages/Newtonsoft.Json
  3. https://www.nuget.org/packages/Microsoft.Extensions.Configuration.Json

Config File

appSettings.json

{
  "BaseUrl": "https://au.itwocx.com/api/20.07/",
  "TenantId": "", 
  "ClientId": "",
  "ResourceId": "52e5f8a4-8b0e-455f-9df4-5beb7c37dd18",
  "User": "name@domain.com",
  "Password": ""
}


Code Sample

using Microsoft.Extensions.Configuration;
using Microsoft.Identity.Client;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security;
using System.Text;
using System.Threading.Tasks;

namespace CX.OAuth.Silent
{
    class Program
    {
        static IConfiguration AppSettings = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appSettings.json", false, true)
                .Build();

        static async Task Main(string[] args)
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);            
            AuthenticationResult authResult = await AuthenticateToAzureAD();
            if (authResult != null)
            {
                Console.WriteLine($"Logged In to AzureAD: {authResult.Account}");

                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri(AppSettings["BaseUrl"]);
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
                    var loginResponse = client.PostAsync("Api/Login/ByUserToken", new StringContent("", Encoding.UTF8, "application/json")).Result;
                    var loginResponseContent = loginResponse.Content.ReadAsStringAsync().Result;

                    if (!string.IsNullOrEmpty(loginResponseContent))
                    {
                        dynamic loginResult = JsonConvert.DeserializeObject(loginResponseContent);
                        bool isSuccess = loginResult.IsSuccess;
                        if (isSuccess)
                        {
                            string sessionKey = loginResult.Key;
                            Console.WriteLine($"SessionKey: {sessionKey}");
                            client.DefaultRequestHeaders.Add("key", sessionKey);
                            dynamic projectResponse = JsonConvert.DeserializeObject(client.GetStringAsync("Api/Project/Get").Result);
                            Console.WriteLine("Project.Get:\n{0}", JsonConvert.SerializeObject(projectResponse, Formatting.Indented));
                        }
                    }
                }
            }
        }

        static async Task<AuthenticationResult> AuthenticateToAzureAD()
        {
            string authority = $"https://login.microsoftonline.com/{AppSettings["TenantId"]}";
            var scopes = new[] { $"{AppSettings["ResourceId"]}/.default" };

            var publicApplication = PublicClientApplicationBuilder.Create(AppSettings["ClientId"]).WithAuthority(authority).WithDefaultRedirectUri().Build();
            AuthenticationResult result = null;

            try
            {
                Console.WriteLine("Logging In Silently...");

                //Recommended
                result = await publicApplication.AcquireTokenByIntegratedWindowsAuth(scopes).ExecuteAsync();

                //Fallback
                //SecureString password = new NetworkCredential("", AppSettings["Password"]).SecurePassword;
                //result = await publicApplication.AcquireTokenByUsernamePassword(scopes, AppSettings["User"], password).ExecuteAsync();
            }
            catch (MsalUiRequiredException ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
                Console.WriteLine("Logging In Interactively...");
                result = await publicApplication.AcquireTokenInteractive(scopes).ExecuteAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
            return result;
        }
    }
}

  • No labels