private static async Task <bool> RemoveGroupOwner(string grpName, string userName)
        {
            try
            {
                // get object id for userPrincipalName
                var userObjectId = GetUserObjectId(userName).GetAwaiter().GetResult();

                // get object id fro group name
                var groupObjectId = GetGroupObjectId(grpName).GetAwaiter().GetResult();

                AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile("appsettings.json");

                // call MS Graph Api function that attaches a member to the group
                var httpClient = new HttpClient();
                var apiCaller  = new ProtectedApiCallHelper(httpClient);
                await apiCaller.DeleteWebApiAndProcessResultASync($"{config.ApiUrl}v1.0/groups/{groupObjectId}/owners/{userObjectId}/$ref",
                                                                  Program.AuthenticationResult.AccessToken);

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
        private static async Task CreateGroup(string jsonGroup)
        {
            AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile("appsettings.json");


            Debug.WriteLine("===================== Create Alvianda group: =======================");

            try
            {
                var httpClient = new HttpClient();
                var apiCaller  = new ProtectedApiCallHelper(httpClient);
                await apiCaller.PostWebApiAndProcessResultASync($"{config.ApiUrl}v1.0/groups",
                                                                jsonGroup,
                                                                Program.AuthenticationResult.AccessToken,
                                                                Display);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            finally
            {
                Debug.WriteLine("========================= End list ==========================================");
            }
        }
        public static async Task <string> GetGroupObjectId(string groupname)
        {
            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/groups", Program.AuthenticationResult.AccessToken, Display);

                // TODO get the group is based on group name (query json result)
                string groupId = string.Empty;
                foreach (var group in JObject.Parse(result)["value"].ToList())
                {
                    if (group["displayName"].ToString() == groupname)
                    {
                        groupId = group["id"].ToString();
                        break;
                    }
                }
                return(groupId);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                return(null);
            }
        }
        private static async Task <bool> AddGroupMember(string grpName, string userName)
        {
            try
            {
                // get object id for userPrincipalName
                var userObjectId = GetUserObjectId(userName).GetAwaiter().GetResult();

                // get object id fro group name
                var groupObjectId = GetGroupObjectId(grpName).GetAwaiter().GetResult();

                AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile("appsettings.json");

                // call MS Graph Api function that attaches a member to the group
                var httpClient = new HttpClient();
                var apiCaller  = new ProtectedApiCallHelper(httpClient);
                var payloadUrl = "{'@odata.id': 'https://graph.microsoft.com/v1.0/directoryObjects/" + userObjectId + "'}";
                await apiCaller.PostWebApiAndProcessResultASync($"{config.ApiUrl}v1.0/groups/{groupObjectId}/members/$ref",
                                                                payloadUrl,
                                                                Program.AuthenticationResult.AccessToken, null);

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
示例#5
0
        private static async Task GetClientApplicationToken()
        {
            AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile("appsettings.json");

            // You can run this sample using ClientSecret or Certificate. The code will differ only when instantiating the IConfidentialClientApplication
            bool isUsingClientSecret = AppUsesClientSecret(config);

            // Even if this is a console application here, a daemon application is a confidential client application
            IConfidentialClientApplication app;

            if (isUsingClientSecret)
            {
                app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
                      .WithClientSecret(config.ClientSecret)
                      .WithAuthority(new Uri(config.Authority))
                      .Build();
            }

            else
            {
                X509Certificate2 certificate = ReadCertificate(config.CertificateName);
                app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
                      .WithCertificate(certificate)
                      .WithAuthority(new Uri(config.Authority))
                      .Build();
            }

            // With client credentials flows the scopes is ALWAYS of the shape "resource/.default", as the
            // application permissions need to be set statically (in the portal or by PowerShell), and then granted by
            // a tenant administrator.
            string[] scopes = new string[] { $"{config.ApiUrl}.default" };

            AuthenticationResult result = null;

            try
            {
                result = await app.AcquireTokenForClient(scopes)
                         .ExecuteAsync();

                Debug.WriteLine("Token acquired");
            }
            catch (MsalServiceException ex) when(ex.Message.Contains("AADSTS70011"))
            {
                // Invalid scope. The scope has to be of the form "https://resourceurl/.default"
                // Mitigation: change the scope to be as expected
                Debug.WriteLine("Scope provided is not supported");
            }

            if (result != null)
            {
                AuthenticationResult = result;
            }
        }
示例#6
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);
            }
        }
        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);
            }
        }