Ejemplo n.º 1
0
        /// <summary>
        /// Filters the existing role Definitions.
        /// If name is not provided, all role definitions are fetched.
        /// </summary>
        /// <param name="name">The role name</param>
        /// <returns>The matched role Definitions</returns>
        public List <PSRoleDefinition> FilterRoleDefinitions(string name, string scope, bool scopeAndBelow = false)
        {
            List <PSRoleDefinition> result = new List <PSRoleDefinition>();

#if !NETSTANDARD
            ListDefinitionFilterParameters parameters = new ListDefinitionFilterParameters
            {
                RoleName        = name,
                AtScopeAndBelow = scopeAndBelow
            };

            result.AddRange(AuthorizationManagementClient.RoleDefinitions.List(scope, parameters).RoleDefinitions.Select(r => r.ToPSRoleDefinition()));
#else
            Rest.Azure.OData.ODataQuery <RoleDefinitionFilter> odataFilter = null;

            if (scopeAndBelow)
            {
                odataFilter = new Rest.Azure.OData.ODataQuery <RoleDefinitionFilter>(item => item.AtScopeAndBelow() && item.RoleName == name);
            }
            else
            {
                odataFilter = new Rest.Azure.OData.ODataQuery <RoleDefinitionFilter>(item => item.RoleName == name);
            }

            result.AddRange(AuthorizationManagementClient.RoleDefinitions.List(
                                scope,
                                odataFilter)
                            .Select(r => r.ToPSRoleDefinition()));
#endif
            return(result);
        }
        public override void ExecuteCmdlet()
        {
            ExecutionBlock(() =>
            {
                if (ObjectId != Guid.Empty)
                {
                    WriteObject(ActiveDirectoryClient.GetApplication(ObjectId.ToString()));
                }
                else
                {
                    Rest.Azure.OData.ODataQuery<Application> odataQueryFilter = null;

                    if (ApplicationId != Guid.Empty)
                    {
                        string appId = ApplicationId.ToString();
                        odataQueryFilter = new Rest.Azure.OData.ODataQuery<Application>(a => a.AppId == appId);
                    }
                    else if (!string.IsNullOrEmpty(DisplayNameStartWith))
                    {
                        odataQueryFilter = new Rest.Azure.OData.ODataQuery<Application>(a => a.DisplayName.StartsWith(DisplayNameStartWith));
                    }
                    else if (!string.IsNullOrEmpty(IdentifierUri))
                    {
                        odataQueryFilter = new Rest.Azure.OData.ODataQuery<Application>(a => a.IdentifierUris.Contains(IdentifierUri));
                    }

                    WriteObject(ActiveDirectoryClient.GetApplicationWithFilters(odataQueryFilter), enumerateCollection: true);
                }
            });
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Fetches all existing role Definitions.
        /// </summary>
        /// <returns>role Definitions</returns>
        public IEnumerable <PSRoleDefinition> GetAllRoleDefinitionsAtScopeAndBelow(string scope, ulong first = ulong.MaxValue, ulong skip = 0)
        {
            var odataQuery = new Rest.Azure.OData.ODataQuery <RoleDefinitionFilter>();

            return(AuthorizationManagementClient.RoleDefinitions.List(scope ?? string.Empty, odataQuery)
                   .Select(r => r.ToPSRoleDefinition()));
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Filters the existing role Definitions by CustomRole.
        /// </summary>
        /// <returns>The custom role Definitions</returns>
        public IEnumerable <PSRoleDefinition> FilterRoleDefinitionsByCustom(string scope, ulong first = ulong.MaxValue, ulong skip = 0)
        {
            var odataQuery = new Rest.Azure.OData.ODataQuery <RoleDefinitionFilter>(filter => filter.Type == AuthorizationClientExtensions.CustomRole);

            return(AuthorizationManagementClient.RoleDefinitions.List(scope, odataQuery: odataQuery)
                   .Select(r => r.ToPSRoleDefinition()));
        }
Ejemplo n.º 5
0
        public override void ExecuteCmdlet()
        {
            ExecutionBlock(() =>
            {
                if (ObjectId != Guid.Empty)
                {
                    WriteObject(ActiveDirectoryClient.GetApplication(ObjectId.ToString()));
                }
                else
                {
                    Rest.Azure.OData.ODataQuery <Application> odataQueryFilter = new Rest.Azure.OData.ODataQuery <Application>();

                    if (ApplicationId != Guid.Empty)
                    {
                        string appId     = ApplicationId.ToString();
                        odataQueryFilter = new Rest.Azure.OData.ODataQuery <Application>(a => a.AppId == appId);
                    }
                    else if (!string.IsNullOrEmpty(DisplayNameStartWith))
                    {
                        odataQueryFilter = new Rest.Azure.OData.ODataQuery <Application>(a => a.DisplayName.StartsWith(DisplayNameStartWith));
                    }
                    else if (!string.IsNullOrEmpty(IdentifierUri))
                    {
                        odataQueryFilter = new Rest.Azure.OData.ODataQuery <Application>(a => a.IdentifierUris.Contains(IdentifierUri));
                    }

                    WriteObject(ActiveDirectoryClient.GetApplicationWithFilters(odataQueryFilter), enumerateCollection: true);
                }
            });
        }
Ejemplo n.º 6
0
 private PSKeyVaultRoleAssignment[] FilterAssignments(PSKeyVaultRoleAssignment[] assignments)
 {
     if (!string.IsNullOrEmpty(RoleDefinitionName))
     {
         var definition = Track2DataClient.GetHsmRoleDefinitions(HsmName, Scope)
                          .FirstOrDefault(x => string.Equals(x.RoleName, RoleDefinitionName, StringComparison.OrdinalIgnoreCase));
         RoleDefinitionId = definition?.Id;
     }
     if (!string.IsNullOrEmpty(SignInName))
     {
         var filter = new ADObjectFilterOptions()
         {
             UPN = SignInName
         };
         var user = ActiveDirectoryClient.FilterUsers(filter).FirstOrDefault();
         ObjectId = user?.Id.ToString();
     }
     if (!string.IsNullOrEmpty(ApplicationId))
     {
         var odataQuery = new Rest.Azure.OData.ODataQuery <Application>(s => string.Equals(s.AppId, ApplicationId, StringComparison.OrdinalIgnoreCase));
         var app        = ActiveDirectoryClient.GetApplicationWithFilters(odataQuery).FirstOrDefault();
         ObjectId = app?.ObjectId.ToString();
     }
     if (!string.IsNullOrEmpty(RoleDefinitionId))
     {
         assignments = assignments.Where(assignment => string.Equals(assignment.RoleDefinitionId, RoleDefinitionId, StringComparison.OrdinalIgnoreCase)).ToArray();
     }
     if (!string.IsNullOrEmpty(ObjectId))
     {
         assignments = assignments.Where(assignment => string.Equals(assignment.PrincipalId, ObjectId, StringComparison.OrdinalIgnoreCase)).ToArray();
     }
     return(assignments);
 }
        /// <summary>
        /// Assign owner role to Blueprint RP (so that we can do deployments)
        /// </summary>
        /// <param name="subscriptionId"></param>
        /// <param name="spnObjectId"></param>
        protected void AssignOwnerPermission(string subscriptionId, string spnObjectId)
        {
            string scope = string.Format(BlueprintConstants.SubscriptionScope, subscriptionId);

            var filter = new Rest.Azure.OData.ODataQuery<RoleAssignmentFilter>();
            filter.SetFilter(a => a.AssignedTo(spnObjectId));

            var roleAssignmentList = AuthorizationManagementClient.RoleAssignments.ListForScopeAsync(scope, filter).GetAwaiter().GetResult();

            var roleAssignment = roleAssignmentList?
                .Where(ra => ra.Id.EndsWith(BlueprintConstants.OwnerRoleDefinitionId))
                .FirstOrDefault();

            if (roleAssignment != null) return;

            var roleAssignmentParams = new RoleAssignmentProperties(
                roleDefinitionId: BlueprintConstants.OwnerRoleDefinitionId, principalId: spnObjectId);

            try
            {
                AuthorizationManagementClient.RoleAssignments.CreateAsync(scope: scope,
                    roleAssignmentName: Guid.NewGuid().ToString(),
                    parameters: new RoleAssignmentCreateParameters(roleAssignmentParams))
                    .GetAwaiter().GetResult();
            }
            catch (Exception ex)
            {
                // ignore if it already exists
                if (ex is CloudException cex && cex.Response.StatusCode != HttpStatusCode.Conflict)
                {
                    throw;
                }
            }
        }
Ejemplo n.º 8
0
 public virtual IEnumerable <PSResource> ListResources(Rest.Azure.OData.ODataQuery <GenericResourceFilter> filter = null, ulong first = ulong.MaxValue, ulong skip = ulong.MinValue)
 {
     return(new GenericPageEnumerable <GenericResource>(
                delegate()
     {
         return ResourceManagementClient.Resources.List(filter);
     }, ResourceManagementClient.Resources.ListNext, first, skip).Select(r => new PSResource(r)));
 }
 public IEnumerable <PSADApplication> GetApplicationWithFilters(Rest.Azure.OData.ODataQuery <Application> odataQueryFilter, ulong first = ulong.MaxValue, ulong skip = 0)
 {
     return(new GenericPageEnumerable <Application>(
                delegate()
     {
         return GraphClient.Applications.List(odataQueryFilter);
     }, GraphClient.Applications.ListNext, first, skip).Select(a => a.ToPSADApplication()));
 }
 public IEnumerable <PSADServicePrincipal> FilterServicePrincipals(Rest.Azure.OData.ODataQuery <ServicePrincipal> odataQuery, ulong first = ulong.MaxValue, ulong skip = 0)
 {
     return(new GenericPageEnumerable <ServicePrincipal>(
                delegate()
     {
         return GraphClient.ServicePrincipals.List(odataQuery);
     }, GraphClient.ServicePrincipals.ListNext, first, skip).Select(s => s.ToPSADServicePrincipal()));
 }
Ejemplo n.º 11
0
        public IEnumerable <PSADServicePrincipal> FilterServicePrincipals(Rest.Azure.OData.ODataQuery <MicrosoftGraphServicePrincipal> odataQuery, int first = int.MaxValue, int skip = 0)
        {
            var response = GraphClient.ServicePrincipals.ListServicePrincipal(
                consistencyLevel: "eventual",
                filter: OdataHelper.GetFilterString(odataQuery)
                );

            return(response.Value.Select(s => s.ToPSADServicePrincipal()));
        }
        public IEnumerable <PSADUser> FilterUsers(ADObjectFilterOptions options, ulong first = ulong.MaxValue, ulong skip = 0)
        {
            if (!string.IsNullOrEmpty(options.Id))
            {
                User user = null;
                try
                {
                    user = GraphClient.Users.Get(Normalize(options.Id));
                }
                catch { /* The user does not exist, ignore the exception. */ }

                if (user != null)
                {
                    return(new List <PSADUser> {
                        user.ToPSADUser()
                    });
                }
            }
            else if (!string.IsNullOrEmpty(options.UPN) || !string.IsNullOrEmpty(options.Mail))
            {
                IPage <User> result = null;
                try
                {
                    string upnOrMail  = Normalize(options.UPN) ?? Normalize(options.Mail);
                    var    odataQuery = new Rest.Azure.OData.ODataQuery <User>(u => u.UserPrincipalName == upnOrMail);
                    result = GraphClient.Users.List(odataQuery);
                }
                catch { /* The user does not exist, ignore the exception. */ }

                if (result != null)
                {
                    return(result.Select(u => u.ToPSADUser()));
                }
            }
            else
            {
                Rest.Azure.OData.ODataQuery <User> odataQuery = null;
                if (!string.IsNullOrEmpty(options.SearchString) && options.SearchString.EndsWith("*"))
                {
                    options.SearchString = options.SearchString.TrimEnd('*');
                    odataQuery           = new Rest.Azure.OData.ODataQuery <User>(u => u.DisplayName.StartsWith(options.SearchString));
                }
                else
                {
                    odataQuery = new Rest.Azure.OData.ODataQuery <User>(u => u.DisplayName == options.SearchString);
                }

                return(new GenericPageEnumerable <User>(
                           delegate()
                {
                    return GraphClient.Users.List(odataQuery.ToString());
                }, GraphClient.Users.ListNext, first, skip).Select(u => u.ToPSADUser()));
            }

            return(new List <PSADUser>());
        }
Ejemplo n.º 13
0
        private string GetRoleAssignmentNameFromFilterParameters()
        {
            // convert definition name to id
            if (ParameterSetName == ParameterSet.DefinitionNameApplicationId ||
                ParameterSetName == ParameterSet.DefinitionNameObjectId ||
                ParameterSetName == ParameterSet.DefinitionNameSignInName)
            {
                var definition = Track2DataClient.GetHsmRoleDefinitions(HsmName, Scope)
                                 .FirstOrDefault(x => string.Equals(x.RoleName, RoleDefinitionName, StringComparison.OrdinalIgnoreCase));
                if (definition == null)
                {
                    throw new ArgumentException(string.Format(Resources.RoleDefinitionNotFound, RoleDefinitionName));
                }
                RoleDefinitionId = definition.Id;
            }

            // convert user sign in name to object id
            if (ParameterSetName == ParameterSet.DefinitionIdSignInName ||
                ParameterSetName == ParameterSet.DefinitionNameSignInName)
            {
                var filter = new ADObjectFilterOptions()
                {
                    UPN = SignInName
                };
                var user = ActiveDirectoryClient.FilterUsers(filter).FirstOrDefault();
                if (user == null)
                {
                    throw new ArgumentException(string.Format(Resources.UserNotFoundBy, SignInName));
                }
                ObjectId = user.Id.ToString();
            }
            // convert service principal app id to object id
            if (ParameterSetName == ParameterSet.DefinitionIdApplicationId ||
                ParameterSetName == ParameterSet.DefinitionNameApplicationId)
            {
                var odataQuery = new Rest.Azure.OData.ODataQuery <Application>(s => string.Equals(s.AppId, ApplicationId, StringComparison.OrdinalIgnoreCase));
                var app        = ActiveDirectoryClient.GetApplicationWithFilters(odataQuery).FirstOrDefault();
                if (app == null)
                {
                    throw new ArgumentException(string.Format(Resources.ApplicationNotFoundBy, ApplicationId));
                }
                ObjectId = app.ObjectId.ToString();
            }

            var roleAssignment = Track2DataClient.GetHsmRoleAssignments(HsmName, Scope)
                                 .FirstOrDefault(assignment => string.Equals(assignment.PrincipalId, ObjectId) && string.Equals(assignment.RoleDefinitionId, RoleDefinitionId));

            if (roleAssignment == null)
            {
                throw new Exception(Resources.RoleAssignmentNotFound);
            }
            else
            {
                return(roleAssignment.Name);
            }
        }
        private IEnumerable <PSKeyVaultIdentityItem> ListByResourceGroup(
            string resourceGroupName,
            Rest.Azure.OData.ODataQuery <GenericResourceFilter> filter,
            ulong first = ulong.MaxValue,
            ulong skip  = ulong.MinValue)
        {
            IResourceManagementClient armClient = ResourceClient;

            return(new GenericPageEnumerable <GenericResource>(() => armClient.ResourceGroups.ListResources(resourceGroupName, filter), armClient.ResourceGroups.ListResourcesNext, first, skip).Select(r => new PSKeyVaultIdentityItem(r)));
        }
Ejemplo n.º 15
0
        public virtual IEnumerable <PSKeyVaultIdentityItem> ListResources(Rest.Azure.OData.ODataQuery <GenericResourceFilter> filter = null, ulong first = ulong.MaxValue, ulong skip = ulong.MinValue)
        {
            IResourceManagementClient armClient = this.ResourceClient;

            return(new GenericPageEnumerable <GenericResource>(
                       delegate()
            {
                return armClient.Resources.List(filter);
            }, armClient.Resources.ListNext, first, skip).Select(r => new PSKeyVaultIdentityItem(r)));
        }
        public virtual Rest.Azure.IPage <GenericResource> ListResources(
            Rest.Azure.OData.ODataQuery <GenericResourceFilter> filter = null,
            string NextPageLink = null)
        {
            IResourceManagementClient armClient = ResourceClient;

            return(string.IsNullOrEmpty(NextPageLink) ?
                   armClient.Resources.List(filter) :
                   armClient.Resources.ListNext(NextPageLink));
        }
Ejemplo n.º 17
0
 /// <summary>
 /// Filters the existing role Definitions.
 /// If scopeAndBelow is true, Will fetch Roledefinitions with scopeAndBelow and provided name.
 /// Otherwise  will fetch Roledefinitions with provided name
 /// </summary>
 /// <param name="name">The role name</param>
 /// <returns>The matched role Definitions</returns>
 public IEnumerable <PSRoleDefinition> FilterRoleDefinitions(string name, string scope, ulong first = ulong.MaxValue, ulong skip = 0)
 {
     Rest.Azure.OData.ODataQuery <RoleDefinitionFilter> odataFilter = new Rest.Azure.OData.ODataQuery <RoleDefinitionFilter>(item => item.RoleName == name);
     return(new GenericPageEnumerable <RoleDefinition>(
                delegate()
     {
         return AuthorizationManagementClient.RoleDefinitions.List(scope, odataFilter);
     }, AuthorizationManagementClient.RoleDefinitions.ListNext, first, skip)
            .Select(r => r.ToPSRoleDefinition()));
 }
Ejemplo n.º 18
0
        private void RunSimpleCmdlet()
        {
            if (this.IsParameterBound(c => c.Tag))
            {
                this.TagName  = TagsHelper.GetTagNameFromParameters(this.Tag, null);
                this.TagValue = TagsHelper.GetTagValueFromParameters(this.Tag, null);
            }

            var expression = QueryFilterBuilder.CreateFilter(
                subscriptionId: null,
                resourceGroup: null,
                resourceType: this.ResourceType,
                resourceName: null,
                tagName: null,
                tagValue: null,
                filter: this.ODataQuery);

            var odataQuery = new Rest.Azure.OData.ODataQuery <GenericResourceFilter>(expression);
            var result     = Enumerable.Empty <PSResource>();

            if (!ShouldListBySubscription(ResourceGroupName, Name))
            {
                result = this.ResourceManagerSdkClient.ListByResourceGroup(this.ResourceGroupName, odataQuery);
            }
            else
            {
                result = this.ResourceManagerSdkClient.ListResources(odataQuery);
            }

            result = TopLevelWildcardFilter(ResourceGroupName, Name, result);

            if (!string.IsNullOrEmpty(this.TagName) && !string.IsNullOrEmpty(this.TagValue))
            {
                result = result.Where(r => r.Tags != null &&
                                      r.Tags.Keys != null &&
                                      r.Tags.Keys.Where(k => string.Equals(k, this.TagName, StringComparison.OrdinalIgnoreCase))
                                      .Any(k => string.Equals(r.Tags[k], this.TagValue, StringComparison.OrdinalIgnoreCase)));
            }
            else if (!string.IsNullOrEmpty(this.TagName))
            {
                result = result.Where(r => r.Tags != null &&
                                      r.Tags.Keys != null &&
                                      r.Tags.Keys.Where(k => string.Equals(k, this.TagName, StringComparison.OrdinalIgnoreCase))
                                      .Any());
            }
            else if (!string.IsNullOrEmpty(this.TagValue))
            {
                result = result.Where(r => r.Tags != null &&
                                      r.Tags.Values != null &&
                                      r.Tags.Values.Where(v => string.Equals(v, this.TagValue, StringComparison.OrdinalIgnoreCase))
                                      .Any());
            }

            WriteObject(result, true);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Filters deny assignments based on the passed options.
        /// </summary>
        /// <param name="options">The filtering options</param>
        /// <param name="currentSubscription">The current subscription</param>
        /// <returns>The filtered deny assignments</returns>
        public List <PSDenyAssignment> FilterDenyAssignments(FilterDenyAssignmentsOptions options, string currentSubscription)
        {
            var    result      = new List <PSDenyAssignment>();
            string principalId = null;

            PSADObject adObject = null;

            Rest.Azure.OData.ODataQuery <DenyAssignmentFilter> odataQuery = null;
            if (options.DenyAssignmentId != Guid.Empty)
            {
                var scope = !string.IsNullOrEmpty(options.Scope) ? options.Scope : AuthorizationHelper.GetSubscriptionScope(currentSubscription);
                return(new List <PSDenyAssignment>
                {
                    AuthorizationManagementClient.DenyAssignments.Get(scope, options.DenyAssignmentId.ToString())
                    .ToPSDenyAssignment(ActiveDirectoryClient, options.ExcludeAssignmentsForDeletedPrincipals)
                });
            }

            if (!string.IsNullOrEmpty(options.DenyAssignmentName))
            {
                odataQuery = new Rest.Azure.OData.ODataQuery <DenyAssignmentFilter>(item => item.DenyAssignmentName == options.DenyAssignmentName);
            }
            else if (options.ADObjectFilter.HasFilter)
            {
                if (string.IsNullOrEmpty(options.ADObjectFilter.Id) || options.ExpandPrincipalGroups)
                {
                    adObject = ActiveDirectoryClient.GetADObject(options.ADObjectFilter);

                    if (adObject == null)
                    {
                        throw new KeyNotFoundException(ProjectResources.PrincipalNotFound);
                    }
                }

                // Filter first by principal
                if (options.ExpandPrincipalGroups)
                {
                    if (!(adObject is PSADUser))
                    {
                        throw new InvalidOperationException(ProjectResources.ExpandGroupsNotSupported);
                    }

                    principalId = adObject.Id.ToString();
                    odataQuery  = new Rest.Azure.OData.ODataQuery <DenyAssignmentFilter>(f => f.AssignedTo(principalId));
                }
                else
                {
                    principalId = string.IsNullOrEmpty(options.ADObjectFilter.Id) ? adObject.Id.ToString() : options.ADObjectFilter.Id;
                    odataQuery  = new Rest.Azure.OData.ODataQuery <DenyAssignmentFilter>(f => f.PrincipalId == principalId);
                }
            }

            result.AddRange(this.FilterDenyAssignmentsByScope(options, odataQuery, currentSubscription));
            return(result);
        }
Ejemplo n.º 20
0
        public static (string, string) GetDetailsFromADObjectId(string objectId, ActiveDirectoryClient adClient)
        {
            var displayName = "";
            var upnOrSpn    = "";
            var objectType  = "Unknown";

            if (adClient == null || string.IsNullOrWhiteSpace(objectId))
            {
                return(displayName, objectType);
            }

            try
            {
                var obj = adClient.GetObjectsByObjectId(new List <string> {
                    objectId
                }).FirstOrDefault();
                if (obj != null)
                {
                    if (obj.Type.Equals("user", StringComparison.InvariantCultureIgnoreCase))
                    {
                        var user = adClient.FilterUsers(new ADObjectFilterOptions {
                            Id = objectId
                        }).FirstOrDefault();
                        displayName = user.DisplayName;
                        upnOrSpn    = user.UserPrincipalName;
                        objectType  = "User";
                    }
                    else if (obj.Type.Equals("serviceprincipal", StringComparison.InvariantCultureIgnoreCase))
                    {
                        var odataQuery       = new Rest.Azure.OData.ODataQuery <Graph.RBAC.Version1_6.Models.ServicePrincipal>(s => s.ObjectId == objectId);
                        var servicePrincipal = adClient.FilterServicePrincipals(odataQuery).FirstOrDefault();
                        displayName = servicePrincipal.DisplayName;
                        upnOrSpn    = servicePrincipal.ServicePrincipalNames.FirstOrDefault();
                        objectType  = "Service Principal";
                    }
                    else if (obj.Type.Equals("group", StringComparison.InvariantCultureIgnoreCase))
                    {
                        var group = adClient.FilterGroups(new ADObjectFilterOptions {
                            Id = objectId
                        }).FirstOrDefault();
                        displayName = group.DisplayName;
                        objectType  = "Group";
                    }
                }
            }
            catch
            {
                // Error occurred. Don't get the friendly name
            }

            return(
                displayName + (!string.IsNullOrWhiteSpace(upnOrSpn) ? (" (" + upnOrSpn + ")") : ""),
                objectType
                );
        }
        private Rest.Azure.IPage <GenericResource> ListByResourceGroup(
            string resourceGroupName,
            Rest.Azure.OData.ODataQuery <GenericResourceFilter> filter = null,
            string NextPageLink = null)
        {
            IResourceManagementClient armClient = ResourceClient;

            return(string.IsNullOrEmpty(NextPageLink) ?
                   armClient.ResourceGroups.ListResources(resourceGroupName, filter) :
                   armClient.ResourceGroups.ListResourcesNext(NextPageLink));
        }
        public string GetObjectIdFromApplicationId(string applicationId)
        {
            var odataQueryFilter = new Rest.Azure.OData.ODataQuery <Application>(a => a.AppId == applicationId);
            var app = GetApplicationWithFilters(odataQueryFilter).SingleOrDefault();

            if (app == null)
            {
                throw new InvalidOperationException(String.Format(ProjectResources.ApplicationWithAppIdDoesntExist, applicationId));
            }
            return(app.ObjectId.ToString());
        }
        public override void ExecuteCmdlet()
        {
            ExecutionBlock(() =>
            {
                var sp = InputObject;
                if (sp == null)
                {
                    IEnumerable <PSADServicePrincipal> result = null;
                    if (this.IsParameterBound(c => c.ApplicationId))
                    {
                        var appId = ApplicationId.ToString();
                        Rest.Azure.OData.ODataQuery <ServicePrincipal> odataQuery = new Rest.Azure.OData.ODataQuery <ServicePrincipal>(s => s.AppId == appId);
                        result = ActiveDirectoryClient.FilterServicePrincipals(odataQuery);
                    }
                    else
                    {
                        ADObjectFilterOptions options = new ADObjectFilterOptions()
                        {
                            SPN = ServicePrincipalName,
                            Id  = ObjectId
                        };

                        result = ActiveDirectoryClient.FilterServicePrincipals(options);
                    }

                    if (result == null)
                    {
                        throw new InvalidOperationException("ServicePrincipal does not exist.");
                    }

                    sp = result.FirstOrDefault();
                }

                // Get AppObjectId
                var applicationObjectId = GetObjectIdFromApplicationId(sp.ApplicationId.ToString());
                ApplicationUpdateParameters parameters = new ApplicationUpdateParameters()
                {
                    DisplayName         = DisplayName,
                    Homepage            = Homepage,
                    IdentifierUris      = (IdentifierUri == null) ? new string[] { } : IdentifierUri,
                    KeyCredentials      = KeyCredential,
                    PasswordCredentials = PasswordCredential
                };

                if (ShouldProcess(target: sp.Id, action: string.Format("Updating properties on application associated with a service principal with object id '{0}'", sp.Id)))
                {
                    ActiveDirectoryClient.UpdateApplication(applicationObjectId, parameters);
                    WriteObject(ActiveDirectoryClient.FilterServicePrincipals(new ADObjectFilterOptions()
                    {
                        Id = applicationObjectId
                    }).FirstOrDefault());
                }
            });
        }
        private string GetObjectIdFromApplicationId(string applicationId)
        {
            var odataQueryFilter = new Rest.Azure.OData.ODataQuery <Application>(a => a.AppId == applicationId);
            var app = ActiveDirectoryClient.GetApplicationWithFilters(odataQueryFilter).SingleOrDefault();

            if (app == null)
            {
                throw new InvalidOperationException(String.Format("Application with AppId '{0}' does not exist.", applicationId));
            }
            return(app.ObjectId);
        }
        public Guid GetObjectIdFromUPN(string upn)
        {
            var odataQueryFilter = new Rest.Azure.OData.ODataQuery <User>(s => s.UserPrincipalName == upn);
            var user             = GraphClient.Users.List(odataQueryFilter.ToString()).SingleOrDefault();

            if (user == null)
            {
                throw new InvalidOperationException(String.Format(ProjectResources.UserWithUPNDoesntExist, upn));
            }

            return(new Guid(user.ObjectId));
        }
        public override void ExecuteCmdlet()
        {
            // convert definition name to id
            if (ParameterSetName == ParameterSet.DefinitionNameApplicationId ||
                ParameterSetName == ParameterSet.DefinitionNameObjectId ||
                ParameterSetName == ParameterSet.DefinitionNameSignInName)
            {
                var definition = Track2DataClient.GetHsmRoleDefinitions(HsmName, Scope)
                                 .FirstOrDefault(x => string.Equals(x.RoleName, RoleDefinitionName, StringComparison.OrdinalIgnoreCase));
                if (definition == null)
                {
                    throw new ArgumentException(string.Format(Resources.RoleDefinitionNotFound, RoleDefinitionName));
                }
                RoleDefinitionId = definition.Id;
            }

            // convert user sign in name to object id
            if (ParameterSetName == ParameterSet.DefinitionIdSignInName ||
                ParameterSetName == ParameterSet.DefinitionNameSignInName)
            {
                var filter = new ADObjectFilterOptions()
                {
                    UPN = SignInName
                };
                var user = ActiveDirectoryClient.FilterUsers(filter).FirstOrDefault();
                if (user == null)
                {
                    throw new ArgumentException(string.Format(Resources.UserNotFoundBy, SignInName));
                }
                ObjectId = user.Id.ToString();
            }
            // convert service principal app id to object id
            if (ParameterSetName == ParameterSet.DefinitionIdApplicationId ||
                ParameterSetName == ParameterSet.DefinitionNameApplicationId)
            {
                var odataQuery = new Rest.Azure.OData.ODataQuery <Application>(s => string.Equals(s.AppId, ApplicationId, StringComparison.OrdinalIgnoreCase));
                var app        = ActiveDirectoryClient.GetApplicationWithFilters(odataQuery).FirstOrDefault();
                if (app == null)
                {
                    throw new ArgumentException(string.Format(Resources.ApplicationNotFoundBy, ApplicationId));
                }
                ObjectId = app.ObjectId.ToString();
            }

            base.ConfirmAction(
                string.Format(Resources.AssignRole, RoleDefinitionName ?? RoleDefinitionId, SignInName ?? ApplicationId ?? ObjectId, Scope),
                HsmName, () =>
            {
                PSKeyVaultRoleAssignment roleAssignment = Track2DataClient.CreateHsmRoleAssignment(HsmName, Scope, RoleDefinitionId, ObjectId);
                GetAssignmentDetails(roleAssignment, HsmName, Scope);
                WriteObject(roleAssignment);
            });
        }
        // Temporary until this code has moved into ActiveDirectoryClient.
        private static string GetObjectIdFromUPN(ActiveDirectoryClient activeDirectoryClient, string upn)
        {
            var odataQueryFilter = new Rest.Azure.OData.ODataQuery <User>(s => s.UserPrincipalName == upn);
            var user             = activeDirectoryClient.GraphClient.Users.List(odataQueryFilter.ToString()).SingleOrDefault();

            if (user == null)
            {
                throw new InvalidOperationException(String.Format("User with UPN '{0}' does not exist.", upn));
            }

            return(user.ObjectId);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Gets the integration account maps by resource group name.
        /// </summary>
        /// <param name="resourceGroupName">The integration account resource group name.</param>
        /// <param name="integrationAccountName">The integration account name.</param>
        /// <param name="mapType">The map type to filter by.</param>
        /// <returns>List of integration account maps.</returns>
        public IPage <IntegrationAccountMap> ListIntegrationAccountMaps(string resourceGroupName, string integrationAccountName, string mapType)
        {
            var filter = new Rest.Azure.OData.ODataQuery <IntegrationAccountMapFilter>();

            if (!string.IsNullOrWhiteSpace(mapType))
            {
                filter.Filter = $"MapType eq '{mapType}'";
            }
            filter.Top = 1000;

            return(this.LogicManagementClient.IntegrationAccountMaps.List(resourceGroupName, integrationAccountName, filter));
        }
        public Guid GetObjectIdFromSPN(string spn)
        {
            var odataQueryFilter = new Rest.Azure.OData.ODataQuery <ServicePrincipal>(s => s.ServicePrincipalNames.Contains(spn));
            var sp = GraphClient.ServicePrincipals.List(odataQueryFilter.ToString()).SingleOrDefault();

            if (sp == null)
            {
                throw new InvalidOperationException(String.Format(ProjectResources.ServicePrincipalWithSPNDoesntExist, spn));
            }

            return(new Guid(sp.ObjectId));
        }
        public override void ExecuteCmdlet()
        {
            ExecutionBlock(() =>
            {
                PSADServicePrincipal servicePrincipal = null;
                if (this.IsParameterBound(c => c.InputObject))
                {
                    ObjectId = InputObject.Id;
                }

                if (!this.IsParameterBound(c => c.ObjectId) && ObjectId != Guid.Empty)
                {
                    IEnumerable <PSADServicePrincipal> result = null;
                    if (this.IsParameterBound(c => c.ApplicationId) || this.IsParameterBound(c => c.ApplicationObject))
                    {
                        var appId = ApplicationObject == null ? ApplicationId.ToString() : ApplicationObject.ApplicationId.ToString();
                        Rest.Azure.OData.ODataQuery <ServicePrincipal> odataQuery = new Rest.Azure.OData.ODataQuery <ServicePrincipal>(s => s.AppId == appId);
                        result = ActiveDirectoryClient.FilterServicePrincipals(odataQuery);
                    }
                    else if (this.IsParameterBound(c => c.ServicePrincipalName) || this.IsParameterBound(c => c.DisplayName))
                    {
                        ADObjectFilterOptions options = new ADObjectFilterOptions()
                        {
                            SPN          = ServicePrincipalName,
                            SearchString = DisplayName
                        };

                        result = ActiveDirectoryClient.FilterServicePrincipals(options);
                    }

                    if (result == null)
                    {
                        throw new ArgumentException(string.Format("Could not find a service principal with the name {0}.", ServicePrincipalName));
                    }

                    ObjectId = result.Select(s => s.Id).FirstOrDefault();
                }


                ConfirmAction(
                    Force.IsPresent,
                    string.Format(ProjectResources.RemovingServicePrincipal, ObjectId),
                    ProjectResources.RemoveServicePrincipal,
                    ObjectId.ToString(),
                    () => servicePrincipal = ActiveDirectoryClient.RemoveServicePrincipal(ObjectId));

                if (PassThru)
                {
                    WriteObject(servicePrincipal);
                }
            });
        }
        public PSADServicePrincipal GetServicePrincipalBySPN(string spn)
        {
            PSADServicePrincipal servicePrincipal = null;

            try
            {
                var odataQuery = new Rest.Azure.OData.ODataQuery <ServicePrincipal>(s => s.ServicePrincipalNames.Contains(spn));
                servicePrincipal = GraphClient.ServicePrincipals.List(odataQuery.ToString()).FirstOrDefault()?.ToPSADServicePrincipal();
            }
            catch { /* The service principal does not exist, ignore the exception. */ }

            return(servicePrincipal);
        }
        public List<PSADGroup> FilterGroups(ADObjectFilterOptions options)
        {
            List<PSADGroup> groups = new List<PSADGroup>();
            ADGroup group = null;

            if (!string.IsNullOrEmpty(options.Id))
            {
                try
                {
                    group = GraphClient.Groups.Get(options.Id);
                }
                catch {  /* The group does not exist, ignore the exception */ }

                if (group != null)
                {
                    groups.Add(group.ToPSADGroup());
                }
            }
            else
            {
                Rest.Azure.IPage<ADGroup> result = null;
                Rest.Azure.OData.ODataQuery<ADGroup> odataQuery = null;

                if (options.Paging)
                {
                    if (string.IsNullOrEmpty(options.NextLink))
                    {
                        if (options.Mail != null)
                        {
                            odataQuery = new Rest.Azure.OData.ODataQuery<ADGroup>(g => g.Mail == options.Mail);
                        }
                        else
                        {
                            odataQuery = new Rest.Azure.OData.ODataQuery<ADGroup>(g => g.DisplayName.StartsWith(options.SearchString));
                        }

                        result = GraphClient.Groups.List(odataQuery);
                    }
                    else
                    {
                        result = GraphClient.Groups.ListNext(options.NextLink);
                    }

                    groups.AddRange(result.Select(g => g.ToPSADGroup()));
                    options.NextLink = result.NextPageLink;
                }
                else
                {

                    if (options.Mail != null)
                    {
                        odataQuery = new Rest.Azure.OData.ODataQuery<ADGroup>(g => g.Mail == options.Mail);
                    }
                    else
                    {
                        odataQuery = new Rest.Azure.OData.ODataQuery<ADGroup>(g => g.DisplayName.StartsWith(options.SearchString));
                    }

                    result = GraphClient.Groups.List(odataQuery);
                    groups.AddRange(result.Select(g => g.ToPSADGroup()));

                    while (!string.IsNullOrEmpty(result.NextPageLink))
                    {
                        result = GraphClient.Groups.ListNext(result.NextPageLink);
                        groups.AddRange(result.Select(g => g.ToPSADGroup()));
                    }
                }
            }

            return groups;
        }
Ejemplo n.º 33
0
        public List<PSADGroup> FilterGroups(ADObjectFilterOptions options)
        {
            List<PSADGroup> groups = new List<PSADGroup>();

            if (!string.IsNullOrEmpty(options.Id))
            {
                try
                {
                    // use GetObjectsByObjectId to handle Redirects in the CSP scenario
                    PSADGroup group = this.GetObjectsByObjectId(new List<string> { options.Id }).FirstOrDefault() as PSADGroup;
                    if (group != null)
                    {
                        groups.Add(group);
                    }
                }
                catch {  /* The group does not exist, ignore the exception */ }
            }
            else
            {
                Rest.Azure.IPage<ADGroup> result = null;
                Rest.Azure.OData.ODataQuery<ADGroup> odataQuery = null;

                if (options.Paging)
                {
                    if (string.IsNullOrEmpty(options.NextLink))
                    {
                        if (options.Mail != null)
                        {
                            odataQuery = new Rest.Azure.OData.ODataQuery<ADGroup>(g => g.Mail == options.Mail);
                        }
                        else
                        {
                            odataQuery = new Rest.Azure.OData.ODataQuery<ADGroup>(g => g.DisplayName.StartsWith(options.SearchString));
                        }

                        result = GraphClient.Groups.List(odataQuery);
                    }
                    else
                    {
                        result = GraphClient.Groups.ListNext(options.NextLink);
                    }

                    groups.AddRange(result.Select(g => g.ToPSADGroup()));
                    options.NextLink = result.NextPageLink;
                }
                else
                {

                    if (options.Mail != null)
                    {
                        odataQuery = new Rest.Azure.OData.ODataQuery<ADGroup>(g => g.Mail == options.Mail);
                    }
                    else
                    {
                        odataQuery = new Rest.Azure.OData.ODataQuery<ADGroup>(g => g.DisplayName.StartsWith(options.SearchString));
                    }

                    result = GraphClient.Groups.List(odataQuery);
                    groups.AddRange(result.Select(g => g.ToPSADGroup()));

                    while (!string.IsNullOrEmpty(result.NextPageLink))
                    {
                        result = GraphClient.Groups.ListNext(result.NextPageLink);
                        groups.AddRange(result.Select(g => g.ToPSADGroup()));
                    }
                }
            }

            return groups;
        }
Ejemplo n.º 34
0
 public string GetObjectIdFromApplicationId(string applicationId)
 {
     var odataQueryFilter = new Rest.Azure.OData.ODataQuery<Application>(a => a.AppId == applicationId);
     var app = GetApplicationWithFilters(odataQueryFilter).SingleOrDefault();
     if (app == null)
     {
         throw new InvalidOperationException(String.Format(ProjectResources.ApplicationWithAppIdDoesntExist, applicationId));
     }
     return app.ObjectId.ToString();
 }
Ejemplo n.º 35
0
        public string GetObjectIdFromSPN(string spn)
        {
            var odataQueryFilter = new Rest.Azure.OData.ODataQuery<ServicePrincipal>(s => s.ServicePrincipalNames.Contains(spn));
            var sp = GraphClient.ServicePrincipals.List(odataQueryFilter).SingleOrDefault();
            if (sp == null)
            {
                throw new InvalidOperationException(String.Format(ProjectResources.ServicePrincipalWithSPNDoesntExist, spn));
            }

            return sp.ObjectId;
        }