/// <summary>
        /// Ensures the group Exists
        /// </summary>
        /// <param name="groupName"></param>
        private async Task <string> EnsureAzureADGroupExists(string groupName)
        {
            string groupId;

            var client = RestClient
                         .Configure()
                         .WithEnvironment(AzureEnvironment.AzureGlobalCloud)
                         .WithLogLevel(HttpLoggingDelegatingHandler.Level.None)
                         .WithCredentials(_authenticationHelper.GetAzureCrendentials())
                         .Build();

            GraphRbacManager graphRbacManager = new GraphRbacManager(client, _appSettings.TenantId);

            IActiveDirectoryGroup group = await graphRbacManager.Groups.GetByNameAsync(groupName);

            if (group == null)
            {
                GroupCreateParameters parameters = new GroupCreateParameters()
                {
                    DisplayName = groupName, MailNickname = groupName
                };

                ADGroupInner groupInner = await graphRbacManager.Groups.Inner.CreateAsync(parameters);

                groupId = groupInner.ObjectId;
            }
            else
            {
                groupId = group.Id;
            }

            return(groupId);
        }
Exemple #2
0
 public static MyGroup Create(IActiveDirectoryGroup aad)
 {
     return(new MyGroup
     {
         MailNickname = aad.Inner.MailNickname,
         Name = aad.Name
     });
 }
Exemple #3
0
        public ICustomActivityResult Execute()
        {
            var auth = GetAuthenticated();
            IActiveDirectoryGroup adGroup = null;
            Guid groupId = Guid.Empty;

            if (Guid.TryParse(groupName, out groupId))
            {
                adGroup = auth.ActiveDirectoryGroups.List().Where(x => x.Id == groupName).FirstOrDefault();
            }
            else
            {
                adGroup = auth.ActiveDirectoryGroups.List().Where(x => x.Name.ToLower() == groupName.ToLower()).FirstOrDefault();
            }

            if (adGroup == null)
            {
                throw new Exception(string.Format("Group with name '{0}' not found", groupName));
            }

            if (memberTypeId == "user" && !string.IsNullOrEmpty(userEmail))
            {
                var users = auth.ActiveDirectoryUsers.List();
                var user  = auth.ActiveDirectoryUsers.List().Where(u => u.UserPrincipalName.ToLower() == userEmail.ToLower()).FirstOrDefault();

                if (user != null && !string.IsNullOrEmpty(user.UserPrincipalName))
                {
                    AddMemeber(adGroup, user);
                }
                else
                {
                    throw new Exception(string.Format("User with email '{0}' not found", userEmail));
                }
            }
            else if (memberTypeId == "role" && !string.IsNullOrEmpty(roleId))
            {
                var sp = auth.ServicePrincipals.List().Where(r => r.Id == roleId).FirstOrDefault();

                if (sp != null)
                {
                    AddMemeber(adGroup, sp);
                }
                else
                {
                    throw new Exception(string.Format("Role with Id '{0}' not found", roleId));
                }
            }
            else
            {
                throw new Exception("You need to provide either a server role or a user");
            }

            return(this.GenerateActivityResult(GetActivityResult));
        }
Exemple #4
0
        private void AddMemeber(IActiveDirectoryGroup adGroup, IActiveDirectoryObject obj)
        {
            var adGroupMembers = adGroup.ListMembers();
            var member         = adGroupMembers.Where(m => m.Id == obj.Id).FirstOrDefault();

            if (member == null)
            {
                adGroup.Update().WithMember(obj.Id).Apply();
            }
            else
            {
                throw new Exception("Member already exist in this group");
            }
        }
Exemple #5
0
        public void CanCRUDGroup()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                IGraphRbacManager manager = TestHelper.CreateGraphRbacManager();
                var userName                           = SdkContext.RandomResourceName("user", 16);
                var spName                             = SdkContext.RandomResourceName("sp", 16);
                var group1Name                         = SdkContext.RandomResourceName("group", 16);
                var group2Name                         = SdkContext.RandomResourceName("group", 16);
                IActiveDirectoryUser  user             = null;
                IServicePrincipal     servicePrincipal = null;
                IActiveDirectoryGroup group1           = null;
                IActiveDirectoryGroup group2           = null;
                try
                {
                    user = manager.Users.Define(userName)
                           .WithEmailAlias(userName)
                           .WithPassword("StrongPass!123")
                           .Create();
                    servicePrincipal = manager.ServicePrincipals.Define(spName)
                                       .WithNewApplication("https://" + spName)
                                       .Create();
                    group1 = manager.Groups.Define(group1Name)
                             .WithEmailAlias(group1Name)
                             .Create();
                    SdkContext.DelayProvider.Delay(15000);
                    group2 = manager.Groups.Define(group2Name)
                             .WithEmailAlias(group2Name)
                             .WithMember(user.Id)
                             .WithMember(servicePrincipal.Id)
                             .WithMember(group1.Id)
                             .Create();

                    Assert.NotNull(group2);
                    Assert.NotNull(group2.Id);
                    var members = group2.ListMembers();
                    Assert.Equal(3, members.Count());
                    var enumerator = members.GetEnumerator();
                    Assert.True(enumerator.MoveNext());
                    Assert.NotNull(enumerator.Current.Id);
                    Assert.True(enumerator.MoveNext());
                    Assert.NotNull(enumerator.Current.Id);
                    Assert.True(enumerator.MoveNext());
                    Assert.NotNull(enumerator.Current.Id);
                    Assert.False(enumerator.MoveNext());
                }
                finally
                {
                    if (servicePrincipal != null)
                    {
                        manager.ServicePrincipals.DeleteById(servicePrincipal.Id);
                    }
                    // cannot delete users or groups from service principal
                    // if (user != null) {
                    //     manager.Users.DeleteById(user.Id);
                    // }
                    // if (group != null) {
                    //     manager.Groups.DeleteById(group.Id);
                    // }
                }
            }
        }
 /// <summary>
 /// Specifies the Active Directory group this access policy is for.
 /// </summary>
 /// <param name="activeDirectoryGroup">The AD group object.</param>
 /// <return>The next stage of access policy definition.</return>
 Microsoft.Azure.Management.KeyVault.Fluent.AccessPolicy.Definition.IWithAttach <Microsoft.Azure.Management.KeyVault.Fluent.Vault.Definition.IWithCreate> Microsoft.Azure.Management.KeyVault.Fluent.AccessPolicy.Definition.IWithIdentity <Microsoft.Azure.Management.KeyVault.Fluent.Vault.Definition.IWithCreate> .ForGroup(IActiveDirectoryGroup activeDirectoryGroup)
 {
     return(this.ForGroup(activeDirectoryGroup));
 }
Exemple #7
0
 public RoleAssignmentImpl ForGroup(IActiveDirectoryGroup activeDirectoryGroup)
 {
     this.objectId = activeDirectoryGroup.Id;
     return(this);
 }
Exemple #8
0
        /**
         * Azure Compute sample for managing virtual machines -
         *   - Create a AAD security group
         *   - Assign AAD security group Contributor role at a resource group
         *   - Create a virtual machine with MSI enabled
         *   - Add virtual machine MSI service principal to the AAD group
         *   - Set custom script in the virtual machine that
         *          - install az cli in the virtual machine
         *          - uses az cli MSI credentials to create a storage account
         *   - Get storage account created through MSI credentials.
         */
        public static void RunSample(IAzure azure)
        {
            var groupName          = Utilities.CreateRandomName("group");
            var roleAssignmentName = SdkContext.RandomGuid();
            var linuxVMName        = Utilities.CreateRandomName("VM1");
            var rgName             = Utilities.CreateRandomName("rgCOMV");
            var pipName            = Utilities.CreateRandomName("pip1");
            var userName           = "******";
            var password           = "******";
            var region             = Region.USWestCentral;

            var           installScript  = "https://raw.githubusercontent.com/Azure/azure-libraries-for-net/master/Samples/Asset/create_resources_with_msi.sh";
            var           installCommand = "bash create_resources_with_msi.sh {stgName} {rgName} {location}";
            List <String> fileUris       = new List <String>();

            fileUris.Add(installScript);
            try
            {
                //=============================================================
                // Create a AAD security group

                Utilities.Log("Creating a AAD security group");

                IActiveDirectoryGroup activeDirectoryGroup = azure.AccessManagement
                                                             .ActiveDirectoryGroups
                                                             .Define(groupName)
                                                             .WithEmailAlias(groupName)
                                                             .Create();

                //=============================================================
                // Assign AAD security group Contributor role at a resource group

                IResourceGroup resourceGroup = azure.ResourceGroups
                                               .Define(rgName)
                                               .WithRegion(region)
                                               .Create();

                SdkContext.DelayProvider.Delay(45 * 1000);

                Utilities.Log("Assigning AAD security group Contributor role to the resource group");

                azure.AccessManagement
                .RoleAssignments
                .Define(roleAssignmentName)
                .ForGroup(activeDirectoryGroup)
                .WithBuiltInRole(BuiltInRole.Contributor)
                .WithResourceGroupScope(resourceGroup)
                .Create();

                Utilities.Log("Assigned AAD security group Contributor role to the resource group");

                //=============================================================
                // Create a Linux VM with MSI enabled for contributor access to the current resource group

                Utilities.Log("Creating a Linux VM with MSI enabled");

                var virtualMachine = azure.VirtualMachines
                                     .Define(linuxVMName)
                                     .WithRegion(region)
                                     .WithNewResourceGroup(rgName)
                                     .WithNewPrimaryNetwork("10.0.0.0/28")
                                     .WithPrimaryPrivateIPAddressDynamic()
                                     .WithNewPrimaryPublicIPAddress(pipName)
                                     .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
                                     .WithRootUsername(userName)
                                     .WithRootPassword(password)
                                     .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                                     .WithOSDiskCaching(CachingTypes.ReadWrite)
                                     .WithSystemAssignedManagedServiceIdentity()
                                     .Create();

                Utilities.Log("Created virtual machine with MSI enabled");
                Utilities.PrintVirtualMachine(virtualMachine);

                //=============================================================
                // Add virtual machine MSI service principal to the AAD group

                Utilities.Log("Adding virtual machine MSI service principal to the AAD group");

                activeDirectoryGroup.Update()
                .WithMember(virtualMachine.SystemAssignedManagedServiceIdentityPrincipalId)
                .Apply();

                Utilities.Log("Added virtual machine MSI service principal to the AAD group");

                Utilities.Log("Waiting 10 minutes to MSI extension in the VM to refresh the token");

                SdkContext.DelayProvider.Delay(10 * 60 * 1000);

                // Prepare custom script to install az cli that uses MSI to create a storage account
                //
                var stgName = Utilities.CreateRandomName("st44");
                installCommand = installCommand
                                 .Replace("{stgName}", stgName)
                                 .Replace("{rgName}", rgName)
                                 .Replace("{location}", region.Name);

                // Update the VM by installing custom script extension.
                //
                Utilities.Log("Installing custom script extension to configure az cli in the virtual machine");
                Utilities.Log("az cli will use MSI credentials to create storage account");

                virtualMachine.Update()
                .DefineNewExtension("CustomScriptForLinux")
                .WithPublisher("Microsoft.OSTCExtensions")
                .WithType("CustomScriptForLinux")
                .WithVersion("1.4")
                .WithMinorVersionAutoUpgrade()
                .WithPublicSetting("fileUris", fileUris)
                .WithPublicSetting("commandToExecute", installCommand)
                .Attach()
                .Apply();

                // Retrieve the storage account created by az cli using MSI credentials
                //
                var storageAccount = azure.StorageAccounts
                                     .GetByResourceGroup(rgName, stgName);

                Utilities.Log("Storage account created by az cli using MSI credential");
                Utilities.PrintStorageAccount(storageAccount);
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + rgName);
                    azure.ResourceGroups.BeginDeleteByName(rgName);
                }
                catch (NullReferenceException)
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
                catch (Exception g)
                {
                    Utilities.Log(g);
                }
            }
        }
 /// <summary>
 /// Specifies the assignee of the role assignment to be a group.
 /// </summary>
 /// <param name="activeDirectoryGroup">The user group.</param>
 /// <return>The next stage in role assignment definition.</return>
 RoleAssignment.Definition.IWithRole RoleAssignment.Definition.IWithAssignee.ForGroup(IActiveDirectoryGroup activeDirectoryGroup)
 {
     return(this.ForGroup(activeDirectoryGroup) as RoleAssignment.Definition.IWithRole);
 }
 /// <summary>
 /// Adds a group as a member in the group.
 /// </summary>
 /// <param name="group">The Active Directory group to add.</param>
 /// <return>The next AD group definition stage.</return>
 ActiveDirectoryGroup.Definition.IWithCreate ActiveDirectoryGroup.Definition.IWithMemberBeta.WithMember(IActiveDirectoryGroup group)
 {
     return(this.WithMember(group));
 }
 /// <summary>
 /// Removes a group as a member in the group.
 /// </summary>
 /// <param name="group">The Active Directory group to remove.</param>
 /// <return>The next AD group update stage.</return>
 ActiveDirectoryGroup.Update.IUpdate ActiveDirectoryGroup.Update.IWithMemberBeta.WithoutMember(IActiveDirectoryGroup group)
 {
     return(this.WithoutMember(group));
 }
        ///GENMHASH:498DF2FE8CE61E58CF671C4DCDF1A6D1:F6952E2299613B074C6F3E2594360B44
        public AccessPolicyImpl ForGroup(IActiveDirectoryGroup group)
        {
            Inner.ObjectId = group.Id;

            return(this);
        }
Exemple #13
0
 /// <summary>
 /// Specifies the Active Directory group this access policy is for.
 /// </summary>
 /// <param name="group">group the AD group object</param>
 /// <returns>the next stage of access policy definition</returns>
 Microsoft.Azure.Management.KeyVault.Fluent.AccessPolicy.UpdateDefinition.IWithAttach <Microsoft.Azure.Management.KeyVault.Fluent.Vault.Update.IUpdate> Microsoft.Azure.Management.KeyVault.Fluent.AccessPolicy.UpdateDefinition.IWithIdentity <Microsoft.Azure.Management.KeyVault.Fluent.Vault.Update.IUpdate> .ForGroup(IActiveDirectoryGroup group)
 {
     return(this.ForGroup(group) as Microsoft.Azure.Management.KeyVault.Fluent.AccessPolicy.UpdateDefinition.IWithAttach <Microsoft.Azure.Management.KeyVault.Fluent.Vault.Update.IUpdate>);
 }
Exemple #14
0
 private static void Log(int level, IActiveDirectoryGroup item)
 {
     Log(level, $"{item.Name}");
     Log(level + 1, $"{item.Inner.MailNickname}");
 }