Exemple #1
0
        private static async Task <AuthenticationResult> Login()
        {
            AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile("appsettings.json");

            AuthenticationResult authResult = null;

            string[] scopes = new string[] { "user.read", "Directory.Read.All", "Directory.ReadWrite.All" };
            try
            {
                var _clientId = config.ClientId;   // this is an app client that allows 'client app' authentication
                var _instance = config.Instance.Replace("{0}", "");
                var _tenant   = config.Tenant;

                _clientApp = PublicClientApplicationBuilder.Create(_clientId)
                             .WithAuthority($"{_instance}{_tenant}")
                             //.WithAuthority(new Uri(config.Authority))
                             .WithDefaultRedirectUri()
                             //.WithRedirectUri("msal2676c812-ca98-4688-ad5c-9dcb92096171://auth")
                             .Build();
                authResult = await Program.PublicClientApp.AcquireTokenInteractive(scopes)
                             .ExecuteAsync();
            }
            //catch (MsalUiRequiredException ex)
            //{
            //    // A MsalUiRequiredException happened on AcquireTokenSilent.
            //    // This indicates you need to call AcquireTokenInteractive to acquire a token
            //    System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");

            //    try
            //    {
            //        authResult = await Program.PublicClientApp.AcquireTokenInteractive(scopes)
            //            //.WithAccount(accounts.FirstOrDefault())
            //            //.WithPrompt(Prompt.SelectAccount)
            //            .ExecuteAsync();
            //    }
            //    catch (MsalException msalex)
            //    {
            //        Debug.WriteLine($"Error Acquiring Token:{System.Environment.NewLine}{msalex}");
            //    }
            //}
            catch (MsalException msalex)
            {
                Debug.WriteLine($"Error Acquiring Token:{System.Environment.NewLine}{msalex}");
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Error Acquiring Token:{System.Environment.NewLine}{ex}");
            }
            return(authResult);
        }
        private static async Task DeleteGroup(string groupName)
        {
            AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile("appsettings.json");

            try
            {
                var groupId = MsGraphFacade.GetGroupObjectId(groupName).GetAwaiter().GetResult();

                var httpClient = new HttpClient();
                var apiCaller  = new ProtectedApiCallHelper(httpClient);
                await apiCaller.DeleteWebApiAndProcessResultASync($"{config.ApiUrl}v1.0/groups/{groupId}", Program.AuthenticationResult.AccessToken);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
Exemple #3
0
        /// <summary>
        /// Checks if the sample is configured for using ClientSecret or Certificate. This method is just for the sake of this sample.
        /// You won't need this verification in your production application since you will be authenticating in AAD using one mechanism only.
        /// </summary>
        /// <param name="config">Configuration from appsettings.json</param>
        /// <returns></returns>
        private static bool AppUsesClientSecret(AuthenticationConfig config)
        {
            string clientSecretPlaceholderValue = "[Enter here a client secret for your application]";
            string certificatePlaceholderValue  = "[Or instead of client secret: Enter here the name of a certificate (from the user cert store) as registered with your application]";

            if (!String.IsNullOrWhiteSpace(config.ClientSecret) && config.ClientSecret != clientSecretPlaceholderValue)
            {
                return(true);
            }

            else if (!String.IsNullOrWhiteSpace(config.CertificateName) && config.CertificateName != certificatePlaceholderValue)
            {
                return(false);
            }

            else
            {
                throw new Exception("You must choose between using client secret or certificate. Please update appsettings.json file.");
            }
        }
        private static async Task GetUsers()
        {
            AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile("appsettings.json");

            Debug.WriteLine("===================== List of Alvianda users: =======================");
            try
            {
                var httpClient = new HttpClient();
                var apiCaller  = new ProtectedApiCallHelper(httpClient);
                await apiCaller.GetWebApiAndProcessResultASync($"{config.ApiUrl}v1.0/users", Program.AuthenticationResult.AccessToken, Display);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            finally
            {
                Debug.WriteLine("========================= End list ==========================================");
            }
        }
        public static async Task <string> GetUserObjectId(string username)
        {
            AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile("appsettings.json");

            try
            {
                var httpClient = new HttpClient();
                var apiCaller  = new ProtectedApiCallHelper(httpClient);
                var result     = await apiCaller.GetWebApiAndReturnResultAsync($"{config.ApiUrl}v1.0/users/{username}", Program.AuthenticationResult.AccessToken, Display);

                // TODO get the group is based on group name (query json result)
                string userId = JObject.Parse(result)["id"].ToString();

                return(userId);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                return(null);
            }
        }