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); }
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); }
/// <summary> /// Specifies that an access role assigned to the identity should be removed. /// </summary> /// <param name="roleAssignment">a role assigned to the identity</param> /// <returns>RoleAssignmentHelper</returns> public RoleAssignmentHelper WithoutAccessTo(IRoleAssignment roleAssignment) { String principalId = roleAssignment.PrincipalId; if (principalId == null || !principalId.Equals(idProvider.PrincipalId, StringComparison.OrdinalIgnoreCase)) { return(this); } else { this.roleAssignmentIdsToRemove.Add(roleAssignment.Id); } return(this); }
public ServicePrincipalImpl WithoutRole(IRoleAssignment roleAssignment) { this.rolesToDelete.Add(roleAssignment.Id); return(this); }
public void CanCRUDServicePrincipalWithRole() { using (var context = FluentMockContext.Start(GetType().FullName)) { IGraphRbacManager manager = TestHelper.CreateGraphRbacManager(); IServicePrincipal servicePrincipal = null; string subscriptionId = TestHelper.CreateResourceManager().SubscriptionId; string authFile = "mytest.azureauth"; string name = SdkContext.RandomResourceName("javasdksp", 20); string rgName = SdkContext.RandomResourceName("rg", 20); try { servicePrincipal = manager.ServicePrincipals.Define(name) .WithNewApplication("http://easycreate.azure.com/" + name) .DefinePasswordCredential("sppass") .WithPasswordValue("StrongPass!12") .Attach() .DefineCertificateCredential("spcert") .WithAsymmetricX509Certificate() .WithPublicKey(File.ReadAllBytes("Assets/myTest.cer")) .WithDuration(TimeSpan.FromDays(100)) .WithAuthFileToExport(new StreamWriter(new FileStream(authFile, FileMode.OpenOrCreate))) .WithPrivateKeyFile("Assets/myTest._pfx") .WithPrivateKeyPassword("Abc123") .Attach() .WithNewRoleInSubscription(BuiltInRole.Contributor, subscriptionId) .Create(); Console.WriteLine(servicePrincipal.Id + " - " + string.Join(", ", servicePrincipal.ServicePrincipalNames)); Assert.NotNull(servicePrincipal.Id); Assert.NotNull(servicePrincipal.ApplicationId); Assert.Equal(2, servicePrincipal.ServicePrincipalNames.Count); Assert.Equal(1, servicePrincipal.PasswordCredentials.Count); Assert.Equal(1, servicePrincipal.CertificateCredentials.Count); SdkContext.DelayProvider.Delay(10000); IResourceManager resourceManager = Microsoft.Azure.Management.ResourceManager.Fluent.ResourceManager.Authenticate( new AzureCredentialsFactory().FromFile(authFile)).WithSubscription(subscriptionId); var group = resourceManager.ResourceGroups.Define(rgName).WithRegion(Region.USWest).Create(); // Update IRoleAssignment ra = servicePrincipal.RoleAssignments.First(); servicePrincipal.Update() .WithoutRole(ra) .WithNewRoleInResourceGroup(BuiltInRole.Contributor, group) .Apply(); SdkContext.DelayProvider.Delay(120000); Assert.NotNull(resourceManager.ResourceGroups.GetByName(group.Name)); try { resourceManager.ResourceGroups.Define(rgName + "2") .WithRegion(Region.USWest).Create(); } catch (Exception) { // expected } } finally { if (servicePrincipal != null) { manager.ServicePrincipals.DeleteById(servicePrincipal.Id); manager.Applications.DeleteById(manager.Applications.GetByName(servicePrincipal.ApplicationId).Id); } } } }
/** * 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); }
/// <summary> /// Removes a role from the service principal. /// </summary> /// <param name="roleAssignment">The role assignment to remove.</param> /// <return>The next stage of the service principal update.</return> ServicePrincipal.Update.IUpdate ServicePrincipal.Update.IWithRoleAssignmentBeta.WithoutRole(IRoleAssignment roleAssignment) { return(this.WithoutRole(roleAssignment) as ServicePrincipal.Update.IUpdate); }
///GENMHASH:EF11EC04DEA31F31CA7F868E3D094F58:7395BD5AAA04C503F691C11E26A6A807 public IdentityImpl WithoutAccess(IRoleAssignment access) { this.roleAssignmentHelper.WithoutAccessTo(access); return(this); }
/** * 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); } } }
/// <summary> /// Specifies that an access role assigned to the identity should be removed. /// </summary> /// <param name="roleAssignment">Describes an existing role assigned to the identity.</param> /// <return>The next stage of the update.</return> Identity.Update.IUpdate Identity.Update.IWithAccess.WithoutAccess(IRoleAssignment roleAssignment) { return(this.WithoutAccess(roleAssignment)); }
/** * 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); } }