public static PSADGroup ToPSADGroup(this MicrosoftGraphGroup group)
 {
     return(new PSADGroup()
     {
         DisplayName = group.DisplayName,
         Id = group.Id,
         DeletionTimestamp = group.DeletedDateTime,
         Type = "Group",
         SecurityEnabled = group.SecurityEnabled,
         MailNickname = !string.IsNullOrEmpty(group.Mail) ? group.Mail : group.AdditionalProperties.ContainsKey("mailNickname") ? group.AdditionalProperties["mailNickname"]?.ToString() : null,
         Description = group.AdditionalProperties.ContainsKey("description") ? group.AdditionalProperties["description"]?.ToString() : null,
         MailEnabled = group.MailEnabled,
         AdditionalProperties = group.AdditionalProperties
     });
 }
Exemple #2
0
        public static IEnumerable <MicrosoftGraphGroup> FilterGroups(this IMicrosoftGraphClient client, MicrosoftObjectFilterOptions options)
        {
            if (!string.IsNullOrEmpty(options.Id))
            {
                try
                {
                    // use GetObjectsByObjectId to handle Redirects in the CSP scenario
                    MicrosoftGraphGroup group = client.Groups.GetGroup(options.Id);
                    if (group != null)
                    {
                        return(new List <MicrosoftGraphGroup> {
                            group
                        });
                    }
                }
                catch { /* The group does not exist, ignore the exception */ }
            }
            else
            {
                ODataQuery <MicrosoftGraphGroup> odataQuery = null;
                if (options.Mail != null)
                {
                    odataQuery = new ODataQuery <MicrosoftGraphGroup>(g => g.Mail == options.Mail);
                }
                else
                {
                    if (!string.IsNullOrEmpty(options.SearchString) && options.SearchString.EndsWith("*"))
                    {
                        options.SearchString = options.SearchString.TrimEnd('*');
                        odataQuery           = new ODataQuery <MicrosoftGraphGroup>(g => g.DisplayName.StartsWith(options.SearchString));
                    }
                    else
                    {
                        odataQuery = new ODataQuery <MicrosoftGraphGroup>(g => g.DisplayName == options.SearchString);
                    }
                }

                return(client.Groups.ListGroup(filter: FormatFilterString(odataQuery)).Value);
            }

            return(new List <MicrosoftGraphGroup>());
        }
Exemple #3
0
        /// <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 ManagedInstanceAdministrator GetActiveDirectoryInformation(string displayName, Guid objectId)
        {
            // Gets the default Tenant id for the subscriptions
            Guid tenantId = GetTenantId();

            // Check for a Azure Active Directory group. Recommended to always use group.
            IEnumerable <MicrosoftGraphGroup> groupList = null;
            MicrosoftGraphGroup group = null;

            var filter = new MicrosoftObjectFilterOptions()
            {
                Id           = (objectId != null && objectId != Guid.Empty) ? objectId.ToString() : null,
                SearchString = displayName,
                Paging       = true,
            };

            // Get a list of groups from Azure Active Directory
            groupList = MicrosoftGraphClient.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 <MicrosoftGraphServicePrincipal> odataQueryFilter;

            if ((objectId != null && objectId != Guid.Empty))
            {
                var applicationIdString = objectId.ToString();
                odataQueryFilter = new Rest.Azure.OData.ODataQuery <MicrosoftGraphServicePrincipal>(a => a.AppId == applicationIdString);
            }
            else
            {
                odataQueryFilter = new Rest.Azure.OData.ODataQuery <MicrosoftGraphServicePrincipal>(a => a.DisplayName == displayName);
            }

            var servicePrincipalList = MicrosoftGraphClient.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
                MicrosoftGraphServicePrincipal 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 ManagedInstanceAdministrator()
                {
                    Login = displayName,
                    Sid = new Guid(app.AppId),
                    TenantId = tenantId
                });
            }

            if (group != null)
            {
                return(new ManagedInstanceAdministrator()
                {
                    Login = group.DisplayName,
                    Sid = new Guid(group.Id),
                    TenantId = tenantId
                });
            }

            // No group or service principal was found. Check for a user
            filter = new MicrosoftObjectFilterOptions()
            {
                Id           = (objectId != null && objectId != Guid.Empty) ? objectId.ToString() : null,
                SearchString = displayName,
                Paging       = true,
            };

            // Get a list of user from Azure Active Directory
            var userList = MicrosoftGraphClient.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 MicrosoftObjectFilterOptions()
                {
                    Id     = (objectId != null && objectId != Guid.Empty) ? objectId.ToString() : null,
                    UPN    = displayName,
                    Paging = true,
                };

                userList = MicrosoftGraphClient.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 MicrosoftObjectFilterOptions()
                {
                    Id     = (objectId != null && objectId != Guid.Empty) ? objectId.ToString() : null,
                    Mail   = displayName,
                    Paging = true,
                };

                userList = MicrosoftGraphClient.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 ManagedInstanceAdministrator()
                {
                    Login = displayName,
                    Sid = new Guid(obj.Id),
                    TenantId = tenantId
                });
            }
        }
Exemple #4
0
        /// <summary>
        /// Update entity in groups
        /// </summary>
        /// <remarks>
        /// Represents an Azure Active Directory object. The directoryObject type is
        /// the base type for many other directory entity types.
        /// </remarks>
        /// <param name='groupId'>
        /// key: id of group
        /// </param>
        /// <param name='body'>
        /// New property values
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="OdataErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse> UpdateGroupWithHttpMessagesAsync(string groupId, MicrosoftGraphGroup body, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (groupId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "groupId");
            }
            if (body == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "body");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("groupId", groupId);
                tracingParameters.Add("body", body);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "UpdateGroup", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + Client.ApiVersion + "/"), "groups/{group-id}").ToString();

            _url = _url.Replace("{group-id}", System.Uri.EscapeDataString(groupId));
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("PATCH");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
            }


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }

            // Serialize Request
            string _requestContent = null;

            if (body != null)
            {
                _requestContent      = Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings);
                _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 204)
            {
                var ex = new OdataErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    OdataError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <OdataError>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new HttpOperationResponse();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
Exemple #5
0
 /// <summary>
 /// Update entity in groups
 /// </summary>
 /// <remarks>
 /// Represents an Azure Active Directory object. The directoryObject type is
 /// the base type for many other directory entity types.
 /// </remarks>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='groupId'>
 /// key: id of group
 /// </param>
 /// <param name='body'>
 /// New property values
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task UpdateGroupAsync(this IGroupsOperations operations, string groupId, MicrosoftGraphGroup body, CancellationToken cancellationToken = default(CancellationToken))
 {
     (await operations.UpdateGroupWithHttpMessagesAsync(groupId, body, null, cancellationToken).ConfigureAwait(false)).Dispose();
 }
Exemple #6
0
 /// <summary>
 /// Update entity in groups
 /// </summary>
 /// <remarks>
 /// Represents an Azure Active Directory object. The directoryObject type is
 /// the base type for many other directory entity types.
 /// </remarks>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='groupId'>
 /// key: id of group
 /// </param>
 /// <param name='body'>
 /// New property values
 /// </param>
 public static void UpdateGroup(this IGroupsOperations operations, string groupId, MicrosoftGraphGroup body)
 {
     operations.UpdateGroupAsync(groupId, body).GetAwaiter().GetResult();
 }
Exemple #7
0
 /// <summary>
 /// Add new entity to groups
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='body'>
 /// New entity
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <MicrosoftGraphGroup> CreateGroupAsync(this IGroupsOperations operations, MicrosoftGraphGroup body, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.CreateGroupWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Exemple #8
0
 /// <summary>
 /// Add new entity to groups
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='body'>
 /// New entity
 /// </param>
 public static MicrosoftGraphGroup CreateGroup(this IGroupsOperations operations, MicrosoftGraphGroup body)
 {
     return(operations.CreateGroupAsync(body).GetAwaiter().GetResult());
 }