/// <summary> /// Assign the role if it does not exists /// </summary> /// <param name="resourceGroupId"></param> /// <param name="roleId"></param> /// <param name="principalId"></param> /// <returns></returns> public async Task AssignRoles(string resourceGroupId, string roleId, string principalId) { var authenticated = Azure .Configure() .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic) .Authenticate(_authenticationHelper.GetAzureCrendentials()).WithSubscription(_appSettings.Subscriptionid); string roleDefinitionId = $"/subscriptions/{_appSettings.Subscriptionid}/providers/Microsoft.Authorization/roleDefinitions/{roleId}"; var roleAssignments = await authenticated.AccessManagement.RoleAssignments.ListByScopeAsync(resourceGroupId); if (roleAssignments != null) { var roleAssignmentsList = roleAssignments.ToList(); var existingAssignment = roleAssignmentsList.Where(x => (x.PrincipalId.Equals(principalId) && x.RoleDefinitionId.Equals(roleDefinitionId))).FirstOrDefault(); if (existingAssignment is default(IRoleAssignment)) { await authenticated.AccessManagement.RoleAssignments .Define(SdkContext.RandomGuid()) .ForObjectId(principalId) .WithRoleDefinition(roleDefinitionId) .WithScope(resourceGroupId) .CreateAsync(); } } }
/// <summary> /// Creates a RBAC role assignment (using role or role definition) for the service principal exposed by IdProvider. /// </summary> /// <param name="roleOrRoleDefinition">The role or role definition.</param> /// <param name="scope">The scope for the role assignment.</param> /// <return>the role assignment if it is created, null if assignment already exists.</return> private async Task <Microsoft.Azure.Management.Graph.RBAC.Fluent.IRoleAssignment> CreateRbacRoleAssignmentIfNotExistsAsync(string roleOrRoleDefinition, string scope, bool isRole, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(this.idProvider.PrincipalId)) { throw new ArgumentNullException("idProvider.PrincipalId"); } string roleAssignmentName = SdkContext.RandomGuid(); try { if (isRole) { return(await rbacManager .RoleAssignments .Define(roleAssignmentName) .ForObjectId(this.idProvider.PrincipalId) .WithBuiltInRole(BuiltInRole.Parse(roleOrRoleDefinition)) .WithScope(scope) .CreateAsync(cancellationToken)); } else { return(await rbacManager .RoleAssignments .Define(roleAssignmentName) .ForObjectId(this.idProvider.PrincipalId) .WithRoleDefinition(roleOrRoleDefinition) .WithScope(scope) .CreateAsync(cancellationToken)); } } catch (CloudException cloudException) { if (cloudException.Body != null && cloudException.Body.Code != null && cloudException.Body.Code.Equals("RoleAssignmentExists", StringComparison.OrdinalIgnoreCase)) { // NOTE: We are unable to lookup the role assignment from principal.RoleAssignments() list // because role assignment object does not contain 'role' name (the roleDefinitionId refer // 'role' using id with GUID). return(null); } throw cloudException; } }
private async Task <IServicePrincipal> SubmitRolesAsync(IServicePrincipal sp, CancellationToken cancellationToken = default(CancellationToken)) { // Delete if (rolesToDelete.Count > 0) { foreach (string roleId in rolesToDelete) { await Manager().RoleAssignments.DeleteByIdAsync(roleId); cachedRoleAssignments.Remove(roleId); } rolesToDelete.Clear(); } // Create if (rolesToCreate.Count > 0) { foreach (KeyValuePair <string, BuiltInRole> role in rolesToCreate) { IRoleAssignment roleAssignment = await manager.RoleAssignments.Define(SdkContext.RandomGuid()) .ForServicePrincipal(sp) .WithBuiltInRole(role.Value) .WithScope(role.Key) .CreateAsync(cancellationToken); cachedRoleAssignments.Add(roleAssignment.Id, roleAssignment); } rolesToCreate.Clear(); } return(sp); }
/** * Azure Users, Groups and Roles sample. * - Create a user * - Assign role to AD user * - Revoke role from AD user * - Get role by scope and role name * - Create service principal * - Assign role to service principal * - Create 2 Active Directory groups * - Add the user, the service principal, and the 1st group as members of the 2nd group */ public static void RunSample(Azure.IAuthenticated authenticated) { string userEmail = Utilities.CreateRandomName("test"); string userName = userEmail.Replace("test", "Test "); string spName = Utilities.CreateRandomName("sp"); string raName1 = SdkContext.RandomGuid(); string raName2 = SdkContext.RandomGuid(); string groupEmail1 = Utilities.CreateRandomName("group1"); string groupEmail2 = Utilities.CreateRandomName("group2"); string groupName1 = groupEmail1.Replace("group1", "Group "); string groupName2 = groupEmail2.Replace("group2", "Group "); String spId = ""; string subscriptionId = authenticated.Subscriptions.List().First().SubscriptionId; Utilities.Log("Selected subscription: " + subscriptionId); // ============================================================ // Create a user Utilities.Log("Creating an Active Directory user " + userName + "..."); var user = authenticated.ActiveDirectoryUsers .Define(userName) .WithEmailAlias(userEmail) .WithPassword("StrongPass!12") .Create(); Utilities.Log("Created Active Directory user " + userName); Utilities.Print(user); // ============================================================ // Assign role to AD user IRoleAssignment roleAssignment1 = authenticated.RoleAssignments .Define(raName1) .ForUser(user) .WithBuiltInRole(BuiltInRole.DnsZoneContributor) .WithSubscriptionScope(subscriptionId) .Create(); Utilities.Log("Created Role Assignment:"); Utilities.Print(roleAssignment1); // ============================================================ // Revoke role from AD user authenticated.RoleAssignments.DeleteById(roleAssignment1.Id); Utilities.Log("Revoked Role Assignment: " + roleAssignment1.Id); // ============================================================ // Get role by scope and role name IRoleDefinition roleDefinition = authenticated.RoleDefinitions .GetByScopeAndRoleName("subscriptions/" + subscriptionId, "Contributor"); Utilities.Print(roleDefinition); // ============================================================ // Create Service Principal IServicePrincipal sp = authenticated.ServicePrincipals.Define(spName) .WithNewApplication("http://" + spName) .Create(); // wait till service principal created and propagated SdkContext.DelayProvider.Delay(15000); Utilities.Log("Created Service Principal:"); Utilities.Print(sp); spId = sp.Id; // ============================================================ // Assign role to Service Principal string defaultSubscription = authenticated.Subscriptions.List().First().SubscriptionId; IRoleAssignment roleAssignment2 = authenticated.RoleAssignments .Define(raName2) .ForServicePrincipal(sp) .WithBuiltInRole(BuiltInRole.Contributor) .WithSubscriptionScope(defaultSubscription) .Create(); Utilities.Log("Created Role Assignment:"); Utilities.Print(roleAssignment2); // ============================================================ // Create Active Directory groups Utilities.Log("Creating Active Directory group " + groupName1 + "..."); var group1 = authenticated.ActiveDirectoryGroups .Define(groupName1) .WithEmailAlias(groupEmail1) .Create(); Utilities.Log("Created Active Directory group " + groupName1); Utilities.Print(group1); var group2 = authenticated.ActiveDirectoryGroups .Define(groupName2) .WithEmailAlias(groupEmail2) .Create(); Utilities.Log("Created Active Directory group " + groupName2); Utilities.Print(group2); Utilities.Log("Adding group members to group " + groupName2 + "..."); group2.Update() .WithMember(user) .WithMember(sp) .WithMember(group1) .Apply(); Utilities.Log("Group members added to group " + groupName2); Utilities.Print(group2); }
/** * 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); } } }
private async Task <IServicePrincipal> SubmitRolesAsync(IServicePrincipal sp, CancellationToken cancellationToken = default(CancellationToken)) { // Delete if (rolesToDelete.Count > 0) { foreach (string roleId in rolesToDelete) { await Manager().RoleAssignments.DeleteByIdAsync(roleId); cachedRoleAssignments.Remove(roleId); } rolesToDelete.Clear(); } // Create if (rolesToCreate.Count > 0) { foreach (KeyValuePair <string, BuiltInRole> role in rolesToCreate) { int limit = 30; while (true) { try { IRoleAssignment roleAssignment = await manager.RoleAssignments.Define(SdkContext.RandomGuid()) .ForServicePrincipal(sp) .WithBuiltInRole(role.Value) .WithScope(role.Key) .CreateAsync(cancellationToken); cachedRoleAssignments.Add(roleAssignment.Id, roleAssignment); break; } catch (CloudException e) { if (--limit < 0) { throw e; } else if (e.Body != null && "PrincipalNotFound".Equals(e.Body.Code, StringComparison.OrdinalIgnoreCase)) { await SdkContext.DelayProvider.DelayAsync((30 - limit) * 1000, cancellationToken); } else { throw e; } } } } rolesToCreate.Clear(); } return(sp); }
/** * Azure Service Principal sample for managing Service Principal - * - Create an Active Directory application * - Create a Service Principal for the application and assign a role * - Export the Service Principal to an authentication file * - Use the file to list subcription virtual machines * - Update the application * - Delete the application and Service Principal. */ public static void RunSample(Azure.IAuthenticated authenticated, AzureEnvironment environment) { string spName = Utilities.CreateRandomName("sp"); string appName = SdkContext.RandomResourceName("app", 20); string appUrl = "https://" + appName; string passwordName1 = SdkContext.RandomResourceName("password", 20); string password1 = "P@ssw0rd"; string passwordName2 = SdkContext.RandomResourceName("password", 20); string password2 = "StrongP@ss!12"; string certName1 = SdkContext.RandomResourceName("cert", 20); string raName = SdkContext.RandomGuid(); string servicePrincipalId = ""; try { // ============================================================ // Create application Utilities.Log("Creating a service principal " + spName + "..."); IServicePrincipal servicePrincipal = authenticated.ServicePrincipals .Define(appName) .WithNewApplication(appUrl) .DefinePasswordCredential(passwordName1) .WithPasswordValue(password1) .Attach() .DefinePasswordCredential(passwordName2) .WithPasswordValue(password2) .Attach() .DefineCertificateCredential(certName1) .WithAsymmetricX509Certificate() .WithPublicKey(File.ReadAllBytes(Path.Combine(Utilities.ProjectPath, "Asset", "NetworkTestCertificate1.cer"))) .WithDuration(TimeSpan.FromDays(1)) .Attach() .Create(); Utilities.Log("Created service principal " + spName + "."); Utilities.Print(servicePrincipal); servicePrincipalId = servicePrincipal.Id; // ============================================================ // Create role assignment Utilities.Log("Creating a Contributor role assignment " + raName + " for the service principal..."); SdkContext.DelayProvider.Delay(15000); IRoleAssignment roleAssignment = authenticated.RoleAssignments .Define(raName) .ForServicePrincipal(servicePrincipal) .WithBuiltInRole(BuiltInRole.Contributor) .WithSubscriptionScope(authenticated.Subscriptions.List().First <ISubscription>().SubscriptionId) .Create(); Utilities.Log("Created role assignment " + raName + "."); Utilities.Print(roleAssignment); // ============================================================ // Verify the credentials are valid Utilities.Log("Verifying password credential " + passwordName1 + " is valid..."); AzureCredentials testCredential = new AzureCredentialsFactory().FromServicePrincipal( servicePrincipal.ApplicationId, password1, authenticated.TenantId, environment); try { Azure.Authenticate(testCredential).WithDefaultSubscription(); Utilities.Log("Verified " + passwordName1 + " is valid."); } catch (Exception e) { Utilities.Log("Failed to verify " + passwordName1 + " is valid. Exception: " + e.Message); } Utilities.Log("Verifying password credential " + passwordName2 + " is valid..."); testCredential = new AzureCredentialsFactory().FromServicePrincipal( servicePrincipal.ApplicationId, password2, authenticated.TenantId, environment); try { Azure.Authenticate(testCredential).WithDefaultSubscription(); Utilities.Log("Verified " + passwordName2 + " is valid."); } catch (Exception e) { Utilities.Log("Failed to verify " + passwordName2 + " is valid. Exception: " + e.Message); } Utilities.Log("Verifying certificate credential " + certName1 + " is valid..."); testCredential = new AzureCredentialsFactory().FromServicePrincipal( servicePrincipal.ApplicationId, Path.Combine(Utilities.ProjectPath, "Asset", "NetworkTestCertificate1.pfx"), "Abc123", authenticated.TenantId, environment); try { Azure.Authenticate(testCredential).WithDefaultSubscription(); Utilities.Log("Verified " + certName1 + " is valid."); } catch (Exception e) { Utilities.Log("Failed to verify " + certName1 + " is valid. Exception: " + e.Message); } // ============================================================ // Revoke access of the 1st password credential Utilities.Log("Revoking access for password credential " + passwordName1 + "..."); servicePrincipal.Update() .WithoutCredential(passwordName1) .Apply(); SdkContext.DelayProvider.Delay(15000); Utilities.Log("Credential revoked."); // ============================================================ // Verify the revoked password credential is no longer valid Utilities.Log("Verifying password credential " + passwordName1 + " is revoked..."); testCredential = new AzureCredentialsFactory().FromServicePrincipal( servicePrincipal.ApplicationId, password1, authenticated.TenantId, environment); try { Azure.Authenticate(testCredential).WithDefaultSubscription(); Utilities.Log("Failed to verify " + passwordName1 + " is revoked."); } catch (Exception e) { Utilities.Log("Verified " + passwordName1 + " is revoked. Exception: " + e.Message); } // ============================================================ // Revoke the role assignment Utilities.Log("Revoking role assignment " + raName + "..."); authenticated.RoleAssignments.DeleteById(roleAssignment.Id); SdkContext.DelayProvider.Delay(5000); // ============================================================ // Verify the revoked password credential is no longer valid Utilities.Log("Verifying password credential " + passwordName2 + " has no access to subscription..."); testCredential = new AzureCredentialsFactory().FromServicePrincipal( servicePrincipal.ApplicationId, password2, authenticated.TenantId, environment); try { Azure.Authenticate(testCredential).WithDefaultSubscription() .ResourceGroups.List(); Utilities.Log("Failed to verify " + passwordName2 + " has no access to subscription."); } catch (Exception e) { Utilities.Log("Verified " + passwordName2 + " has no access to subscription. Exception: " + e.Message); } } catch (Exception f) { Utilities.Log(f.Message); } finally { try { Utilities.Log("Deleting application: " + appName); authenticated.ServicePrincipals.DeleteById(servicePrincipalId); Utilities.Log("Deleted application: " + appName); } catch (Exception e) { Utilities.Log("Did not create applications in Azure. No clean up is necessary. Exception: " + e.Message); } } }
///GENMHASH:DF5070CC0911A10D9AF3A4D384895BCF:0348450E13F50AE1A527DEF8E5E33A3A public SqlDatabaseImportExportResponseImpl(ImportExportResponseInner innerObject) : base(innerObject) { this.key = SdkContext.RandomGuid(); }
/** * Azure Users, Groups and Roles sample. * - List users * - Get user by email * - Assign role to AD user * - Revoke role from AD user * - Get role by scope and role name * - List roles * - List Active Directory groups. */ public static void RunSample(Azure.IAuthenticated authenticated) { string subscriptionId = authenticated.Subscriptions.List().First().SubscriptionId; Utilities.Log("Selected subscription: " + subscriptionId); string raName1 = SdkContext.RandomGuid(); // ============================================================ // List users var users = authenticated.ActiveDirectoryUsers.List(); Utilities.Log("Active Directory Users:"); foreach (var user in users) { Utilities.Print(user); } // ============================================================ // Get user by email IActiveDirectoryUser adUser = authenticated.ActiveDirectoryUsers.GetByName("*****@*****.**"); Utilities.Log("Found User with email \"[email protected]\": "); Utilities.Print(adUser); // ============================================================ // Assign role to AD user IRoleAssignment roleAssignment1 = authenticated.RoleAssignments .Define(raName1) .ForUser(adUser) .WithBuiltInRole(BuiltInRole.DnsZoneContributor) .WithSubscriptionScope(subscriptionId) .Create(); Utilities.Log("Created Role Assignment:"); Utilities.Print(roleAssignment1); // ============================================================ // Revoke role from AD user authenticated.RoleAssignments.DeleteById(roleAssignment1.Id); Utilities.Log("Revoked Role Assignment: " + roleAssignment1.Id); // ============================================================ // Get role by scope and role name IRoleDefinition roleDefinition = authenticated.RoleDefinitions .GetByScopeAndRoleName("subscriptions/" + subscriptionId, "Contributor"); Utilities.Print(roleDefinition); // ============================================================ // List roles var roles = authenticated.RoleDefinitions .ListByScope("subscriptions/" + subscriptionId); Utilities.Log("Roles: "); foreach (var role in roles) { Utilities.Print(role); } // ============================================================ // List Active Directory groups var groups = authenticated.ActiveDirectoryGroups.List(); Utilities.Log("Active Directory Groups:"); foreach (var group in groups) { Utilities.Print(group); } }