/// <summary> /// Ensures the service principal. /// </summary> /// <returns>PSADServicePrincipal.</returns> public PSADServicePrincipal EnsureServicePrincipal() { string applicationId = KailaniAppId.ToString(); var servicePrincipals = ActiveDirectoryClient.FilterServicePrincipals(new ODataQuery <ServicePrincipal>(s => s.AppId == applicationId)); PSADServicePrincipal servicePrincipal = servicePrincipals.FirstOrDefault(); if (servicePrincipal == null) { VerboseLogger.Invoke(StorageSyncResources.CreateServicePrincipalMessage); // Create an application and get the applicationId var passwordCredential = new PSADPasswordCredential() { StartDate = DateTime.Now, EndDate = DateTime.Now.AddYears(1), KeyId = Guid.NewGuid(), Password = SecureStringExtensions.ConvertToString(Guid.NewGuid().ToString().ConvertToSecureString()) }; var createParameters = new CreatePSServicePrincipalParameters { ApplicationId = KailaniAppId, AccountEnabled = true, PasswordCredentials = new PSADPasswordCredential[] { passwordCredential } }; servicePrincipal = ActiveDirectoryClient.CreateServicePrincipal(createParameters); } return(servicePrincipal); }
/// <summary> /// Ensures the service principal. /// </summary> /// <returns>PSADServicePrincipal.</returns> public PSADServicePrincipal EnsureServicePrincipal() { string applicationId = CurrentApplicationId.ToString(); string appObjectId = ActiveDirectoryClient.GetServicePrincipalsIdByAppId(CurrentApplicationId); PSADServicePrincipal servicePrincipal = ActiveDirectoryClient.GetServicePrincipalByObjectId(appObjectId); if (servicePrincipal == null) { VerboseLogger.Invoke(StorageSyncResources.CreateServicePrincipalMessage); // Create an application and get the applicationId var passwordCredential = new PSADPasswordCredential() { StartDate = DateTime.Now, EndDate = DateTime.Now.AddYears(1), KeyId = Guid.NewGuid(), Password = SecureStringExtensions.ConvertToString(Guid.NewGuid().ToString().ConvertToSecureString()) }; var createParameters = new CreatePSServicePrincipalParameters { ApplicationId = CurrentApplicationId, AccountEnabled = bool.TrueString, PasswordCredentials = new PSADPasswordCredential[] { passwordCredential } }; servicePrincipal = ActiveDirectoryClient.CreateServicePrincipal(createParameters); } return(servicePrincipal); }
/// <summary> /// Executes the cmdlet. /// </summary> public override void ExecuteCmdlet() { base.ExecuteCmdlet(); ExecuteClientAction(() => { // Validate Storage Account Resource Id var storageAccountResourceIdentifier = new ResourceIdentifier(StorageAccountResourceId); if (string.IsNullOrEmpty(storageAccountResourceIdentifier?.ResourceName)) { throw new PSArgumentException(nameof(StorageAccountResourceId)); } PSADServicePrincipal servicePrincipal = StorageSyncClientWrapper.EnsureServicePrincipal(); RoleAssignment roleAssignment = StorageSyncClientWrapper.EnsureRoleAssignment(servicePrincipal, StorageAccountResourceId); var parentResourceIdentifier = default(ResourceIdentifier); if (this.IsParameterBound(c => c.ParentResourceId)) { parentResourceIdentifier = new ResourceIdentifier(ParentResourceId); if (!string.Equals(StorageSyncConstants.SyncGroupType, parentResourceIdentifier.ResourceType, System.StringComparison.OrdinalIgnoreCase)) { throw new PSArgumentException(StorageSyncResources.MissingParentResourceIdErrorMessage); } } var createParameters = new CloudEndpointCreateParameters() { StorageAccountResourceId = StorageAccountResourceId, AzureFileShareName = AzureFileShareName, StorageAccountTenantId = (StorageAccountTenantId ?? DefaultContext.Tenant?.Id) }; string resourceGroupName = ResourceGroupName ?? ParentObject?.ResourceGroupName ?? parentResourceIdentifier.ResourceGroupName; string storageSyncServiceName = StorageSyncServiceName ?? ParentObject?.StorageSyncServiceName ?? parentResourceIdentifier.GetParentResourceName(StorageSyncConstants.StorageSyncServiceTypeName, 0); string syncGroupName = SyncGroupName ?? ParentObject?.SyncGroupName ?? parentResourceIdentifier.ResourceName; Target = string.Join("/", resourceGroupName, storageSyncServiceName, syncGroupName, Name); if (ShouldProcess(Target, ActionMessage)) { StorageSyncModels.CloudEndpoint resource = StorageSyncClientWrapper.StorageSyncManagementClient.CloudEndpoints.Create( resourceGroupName, storageSyncServiceName, syncGroupName, Name, createParameters); WriteObject(resource); } }); }
/// <summary> /// Ensures the role assignment. /// </summary> /// <param name="serverPrincipal">The server principal.</param> /// <param name="storageAccountSubscriptionId">The storage account subscription identifier.</param> /// <param name="storageAccountResourceId">The storage account resource identifier.</param> /// <returns>RoleAssignment.</returns> public RoleAssignment EnsureRoleAssignment(PSADServicePrincipal serverPrincipal, string storageAccountSubscriptionId, string storageAccountResourceId) { string currentSubscriptionId = AuthorizationManagementClient.SubscriptionId; bool hasMismatchSubscription = currentSubscriptionId != storageAccountSubscriptionId; try { if (hasMismatchSubscription) { AuthorizationManagementClient.SubscriptionId = storageAccountSubscriptionId; } var resourceIdentifier = new ResourceIdentifier(storageAccountResourceId); string roleDefinitionScope = "/"; RoleDefinition roleDefinition = AuthorizationManagementClient.RoleDefinitions.Get(roleDefinitionScope, BuiltInRoleDefinitionId); var serverPrincipalId = serverPrincipal.Id.ToString(); var roleAssignments = AuthorizationManagementClient.RoleAssignments .ListForResource( resourceIdentifier.ResourceGroupName, ResourceIdentifier.GetProviderFromResourceType(resourceIdentifier.ResourceType), resourceIdentifier.ParentResource ?? "/", ResourceIdentifier.GetTypeFromResourceType(resourceIdentifier.ResourceType), resourceIdentifier.ResourceName, odataQuery: new ODataQuery <RoleAssignmentFilter>(f => f.AssignedTo(serverPrincipalId))); var roleAssignmentScope = storageAccountResourceId; Guid roleAssignmentId = StorageSyncResourceManager.GetGuid(); RoleAssignment roleAssignment = roleAssignments.FirstOrDefault(); if (roleAssignment == null) { VerboseLogger.Invoke(StorageSyncResources.CreateRoleAssignmentMessage); var createParameters = new RoleAssignmentCreateParameters { Properties = new RoleAssignmentProperties { PrincipalId = serverPrincipalId, RoleDefinitionId = AuthorizationHelper.ConstructFullyQualifiedRoleDefinitionIdFromSubscriptionAndIdAsGuid(resourceIdentifier.Subscription, BuiltInRoleDefinitionId) } }; roleAssignment = AuthorizationManagementClient.RoleAssignments.Create(roleAssignmentScope, roleAssignmentId.ToString(), createParameters); StorageSyncResourceManager.Wait(); } return(roleAssignment); } finally { if (hasMismatchSubscription) { AuthorizationManagementClient.SubscriptionId = currentSubscriptionId; } } }
public PSADServicePrincipalWrapper(PSADServicePrincipal sp) { if (sp != null) { ApplicationId = sp.ApplicationId; DisplayName = sp.DisplayName; Id = sp.Id; ServicePrincipalNames = sp.ServicePrincipalNames; Type = sp.Type; } }
/// <summary> /// Verifies that the Azure Active Directory user or group exists, and will get the object id if it is not set. /// </summary> /// <param name="displayName">Azure Active Directory user or group display name</param> /// <param name="objectId">Azure Active Directory user or group object id</param> /// <returns></returns> protected ManagedInstanceExternalAdministrator GetActiveDirectoryInformation(ManagedInstanceExternalAdministrator input) { if (input == null || string.IsNullOrEmpty(input.Login)) { return(null); } Guid? objectId = input.Sid; string displayName = input.Login; bool? adOnlyAuth = input.AzureADOnlyAuthentication; // Gets the default Tenant id for the subscriptions Guid tenantId = GetTenantId(); // Check for a Azure Active Directory group. Recommended to always use group. IEnumerable <PSADGroup> groupList = null; PSADGroup group = null; var filter = new ADObjectFilterOptions() { Id = (objectId != null && objectId != Guid.Empty) ? objectId.ToString() : null, SearchString = displayName, Paging = true, }; // Get a list of groups from Azure Active Directory groupList = ActiveDirectoryClient.FilterGroups(filter).Where(gr => string.Equals(gr.DisplayName, displayName, StringComparison.OrdinalIgnoreCase)); if (groupList != null && groupList.Count() > 1) { // More than one group was found with that display name. throw new ArgumentException(string.Format(Microsoft.Azure.Commands.Sql.Properties.Resources.ADGroupMoreThanOneFound, displayName)); } else if (groupList != null && groupList.Count() == 1) { // Only one group was found. Get the group display name and object id group = groupList.First(); // Only support Security Groups if (group.SecurityEnabled.HasValue && !group.SecurityEnabled.Value) { throw new ArgumentException(string.Format(Microsoft.Azure.Commands.Sql.Properties.Resources.InvalidADGroupNotSecurity, displayName)); } } // Lookup for serviceprincipals ODataQuery <ServicePrincipal> odataQueryFilter; if ((objectId != null && objectId != Guid.Empty)) { var applicationIdString = objectId.ToString(); odataQueryFilter = new Rest.Azure.OData.ODataQuery <ServicePrincipal>(a => a.AppId == applicationIdString); } else { odataQueryFilter = new Rest.Azure.OData.ODataQuery <ServicePrincipal>(a => a.DisplayName == displayName); } var servicePrincipalList = ActiveDirectoryClient.FilterServicePrincipals(odataQueryFilter); if (servicePrincipalList != null && servicePrincipalList.Count() > 1) { // More than one service principal was found. throw new ArgumentException(string.Format(Microsoft.Azure.Commands.Sql.Properties.Resources.ADApplicationMoreThanOneFound, displayName)); } else if (servicePrincipalList != null && servicePrincipalList.Count() == 1) { // Only one user was found. Get the user display name and object id PSADServicePrincipal app = servicePrincipalList.First(); if (displayName != null && string.CompareOrdinal(displayName, app.DisplayName) != 0) { throw new ArgumentException(string.Format(Microsoft.Azure.Commands.Sql.Properties.Resources.ADApplicationDisplayNameMismatch, displayName, app.DisplayName)); } if (group != null) { throw new ArgumentException(string.Format(Microsoft.Azure.Commands.Sql.Properties.Resources.ADDuplicateGroupAndApplicationFound, displayName)); } return(new ManagedInstanceExternalAdministrator() { Login = displayName, Sid = app.ApplicationId, TenantId = tenantId, PrincipalType = "Application", AzureADOnlyAuthentication = adOnlyAuth }); } if (group != null) { return(new ManagedInstanceExternalAdministrator() { Login = group.DisplayName, Sid = group.Id, TenantId = tenantId, PrincipalType = "Group", AzureADOnlyAuthentication = adOnlyAuth }); } // No group or service principal was found. Check for a user filter = new ADObjectFilterOptions() { Id = (objectId != null && objectId != Guid.Empty) ? objectId.ToString() : null, SearchString = displayName, Paging = true, }; // Get a list of user from Azure Active Directory var userList = ActiveDirectoryClient.FilterUsers(filter).Where(gr => string.Equals(gr.DisplayName, displayName, StringComparison.OrdinalIgnoreCase)); // No user was found. Check if the display name is a UPN if (userList == null || userList.Count() == 0) { // Check if the display name is the UPN filter = new ADObjectFilterOptions() { Id = (objectId != null && objectId != Guid.Empty) ? objectId.ToString() : null, UPN = displayName, Paging = true, }; userList = ActiveDirectoryClient.FilterUsers(filter).Where(gr => string.Equals(gr.UserPrincipalName, displayName, StringComparison.OrdinalIgnoreCase)); } // No user was found. Check if the display name is a guest user. if (userList == null || userList.Count() == 0) { // Check if the display name is the UPN filter = new ADObjectFilterOptions() { Id = (objectId != null && objectId != Guid.Empty) ? objectId.ToString() : null, Mail = displayName, Paging = true, }; userList = ActiveDirectoryClient.FilterUsers(filter); } // No user was found if (userList == null || userList.Count() == 0) { throw new ArgumentException(string.Format(Microsoft.Azure.Commands.Sql.Properties.Resources.ADObjectNotFound, displayName)); } else if (userList.Count() > 1) { // More than one user was found. throw new ArgumentException(string.Format(Microsoft.Azure.Commands.Sql.Properties.Resources.ADUserMoreThanOneFound, displayName)); } else { // Only one user was found. Get the user display name and object id var obj = userList.First(); return(new ManagedInstanceExternalAdministrator() { Login = displayName, Sid = obj.Id, TenantId = tenantId, PrincipalType = "User", AzureADOnlyAuthentication = adOnlyAuth }); } }