Пример #1
0
        /// <summary>
        /// Disables Site Classifications settings for the target tenant
        /// </summary>
        /// <param name="accessToken">The OAuth accessToken for Microsoft Graph with Azure AD</param>
        /// <param name="azureEnvironment">Defines the Azure Cloud Deployment. This is used to determine the MS Graph EndPoint to call which differs per Azure Cloud deployments. Defaults to Production (graph.microsoft.com).</param>
        public static void DisableSiteClassifications(string accessToken, AzureEnvironment azureEnvironment = AzureEnvironment.Production)
        {
            if (string.IsNullOrEmpty(accessToken))
            {
                throw new ArgumentException("Specify a valid accesstoken", nameof(accessToken));
            }
            // GET https://graph.microsoft.com/beta/settings
            string directorySettingsUrl  = $"{GraphHttpClient.GetGraphEndPointUrl(azureEnvironment,true)}settings";
            var    directorySettingsJson = GraphHttpClient.MakeGetRequestForString(directorySettingsUrl, accessToken);
            var    directorySettings     = JsonConvert.DeserializeObject <DirectorySettingTemplates>(directorySettingsJson);

            // Retrieve the setinngs for "Group.Unified"
            var unifiedGroupSetting = directorySettings.Templates.FirstOrDefault(t => t.DisplayName == "Group.Unified");

            if (unifiedGroupSetting != null)
            {
                // DELETE https://graph.microsoft.com/beta/settings
                string deleteDirectorySettingUrl = $"{GraphHttpClient.GetGraphEndPointUrl(azureEnvironment, true)}settings/{unifiedGroupSetting.Id}";
                GraphHttpClient.MakeDeleteRequest(
                    deleteDirectorySettingUrl,
                    accessToken: accessToken);
            }
            else
            {
                throw new ApplicationException("Missing DirectorySettingTemplate for \"Group.Unified\"");
            }
        }
Пример #2
0
        /// <summary>
        /// Enables Site Classifications for the target tenant
        /// </summary>
        /// <param name="accessToken">The OAuth accessToken for Microsoft Graph with Azure AD</param>
        /// <param name="azureEnvironment">Defines the Azure Cloud Deployment. This is used to determine the MS Graph EndPoint to call which differs per Azure Cloud deployments. Defaults to Production (graph.microsoft.com).</param>
        /// <returns>The list of Site Classification values</returns>
        public static SiteClassificationsSettings GetSiteClassificationsSettings(string accessToken, AzureEnvironment azureEnvironment = AzureEnvironment.Production)
        {
            if (string.IsNullOrEmpty(accessToken))
            {
                throw new ArgumentException("Specify a valid accesstoken", nameof(accessToken));
            }
            // GET https://graph.microsoft.com/beta/directorySettingTemplates
            string directorySettingsUrl  = $"{GraphHttpClient.GetGraphEndPointUrl(azureEnvironment,true)}settings";
            var    directorySettingsJson = GraphHttpClient.MakeGetRequestForString(directorySettingsUrl, accessToken);
            var    directorySettings     = JsonConvert.DeserializeObject <DirectorySettingTemplates>(directorySettingsJson);

            // Retrieve the setinngs for "Group.Unified"
            var unifiedGroupSetting = directorySettings.Templates.FirstOrDefault(t => t.DisplayName == "Group.Unified");

            if (unifiedGroupSetting != null)
            {
                var siteClassificationsSettings = new SiteClassificationsSettings();
                var classificationList          = unifiedGroupSetting.SettingValues.FirstOrDefault(v => v.Name == "ClassificationList");
                if (classificationList != null)
                {
                    siteClassificationsSettings.Classifications = classificationList.Value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                }
                var guidanceUrl = unifiedGroupSetting.SettingValues.First(v => v.Name == "UsageGuidelinesUrl");
                if (guidanceUrl != null)
                {
                    siteClassificationsSettings.UsageGuidelinesUrl = guidanceUrl.Value;
                }
                var defaultClassification = unifiedGroupSetting.SettingValues.First(v => v.Name == "DefaultClassification");
                if (defaultClassification != null)
                {
                    siteClassificationsSettings.DefaultClassification = defaultClassification.Value;
                }
                return(siteClassificationsSettings);
            }
            else
            {
                throw new ApplicationException("Missing DirectorySettingTemplate for \"Group.Unified\"");
            }
        }
Пример #3
0
        /// <summary>
        /// Retrieves a temporary access pass for the provided user
        /// </summary>
        /// <param name="accessToken">The OAuth 2.0 Access Token to use for invoking the Microsoft Graph</param>
        /// <param name="userId">Id or user principal name of the user to request the access pass for</param>
        /// <param name="startDateTime">Date and time at which this access pass should become valid. Optional. If not provided, it immediately become valid.</param>
        /// <param name="lifeTimeInMinutes">Durationin minutes during which this access pass will be valid. Optional. If not provided, the default configured in Azure Active Directory will be used.</param>
        /// <param name="isUsableOnce">Boolean indicating if the access pass can be used to only log in once or repetitively during the lifetime of the access pass. Optional. If not provided, the default configured in Azure Active Directory will be used.</param>
        /// <param name="retryCount">Number of times to retry the request in case of throttling. Optional.</param>
        /// <param name="delay">Milliseconds to wait before retrying the request. The delay will be increased (doubled) every retry. Optional.</param>
        /// <param name="azureEnvironment">The type of environment to connect to</param>
        /// <returns>A temporary access pass for the provided user or NULL if unable to create a temporary access pass</returns>
        public static Model.TemporaryAccessPassResponse RequestTemporaryAccessPass(string accessToken, string userId, DateTime?startDateTime = null, int?lifeTimeInMinutes = null, bool?isUsableOnce = null, int retryCount = 10, int delay = 500, AzureEnvironment azureEnvironment = AzureEnvironment.Production)
        {
            if (String.IsNullOrEmpty(accessToken))
            {
                throw new ArgumentNullException(nameof(accessToken));
            }
            if (String.IsNullOrEmpty(userId))
            {
                throw new ArgumentNullException(nameof(userId));
            }

            // Build the request body for the access pass
            var temporaryAccessPassAuthenticationMethod = new Model.TemporaryAccessPassRequest
            {
                StartDateTime     = startDateTime?.ToUniversalTime(),
                LifetimeInMinutes = lifeTimeInMinutes,
                IsUsableOnce      = isUsableOnce
            };

            try
            {
                // Request the access pass
                var response = GraphHttpClient.MakePostRequestForString(
                    requestUrl: $"{GraphHttpClient.GetGraphEndPointUrl(azureEnvironment, beta: true)}users/{userId}/authentication/temporaryAccessPassMethods",
                    content: temporaryAccessPassAuthenticationMethod,
                    contentType: "application/json",
                    accessToken: accessToken);

                // Parse and return the response
                var accessPassResponse = JsonConvert.DeserializeObject <Model.TemporaryAccessPassResponse>(response);
                return(accessPassResponse);
            }
            catch (ServiceException ex)
            {
                Log.Error(Constants.LOGGING_SOURCE, CoreResources.GraphExtensions_ErrorOccured, ex.Error.Message);
                throw;
            }
        }
Пример #4
0
        /// <summary>
        /// Enables Site Classifications for the target tenant
        /// </summary>
        /// <param name="accessToken">The OAuth accessToken for Microsoft Graph with Azure AD</param>
        /// <param name="classificationsList">The list of classification values</param>
        /// <param name="defaultClassification">The default classification</param>
        /// <param name="usageGuidelinesUrl">The URL of a guidance page</param>
        /// <param name="azureEnvironment">Defines the Azure Cloud Deployment. This is used to determine the MS Graph EndPoint to call which differs per Azure Cloud deployments. Defaults to Production (graph.microsoft.com).</param>
        public static void EnableSiteClassifications(string accessToken, IEnumerable <string> classificationsList, string defaultClassification = "", string usageGuidelinesUrl = "", AzureEnvironment azureEnvironment = AzureEnvironment.Production)
        {
            if (string.IsNullOrEmpty(accessToken))
            {
                throw new ArgumentException("Specify a valid accesstoken", nameof(accessToken));
            }
            if (classificationsList == null || !classificationsList.Any())
            {
                throw new ArgumentException("Specify one or more classifications", nameof(classificationsList));
            }
            if (usageGuidelinesUrl == null)
            {
                throw new ArgumentException("Specify a valid URL or an empty string to not set this value", nameof(usageGuidelinesUrl));
            }
            if (!classificationsList.Contains(defaultClassification))
            {
                throw new ArgumentException("The default classification specified is not available in the list of specified classifications", nameof(defaultClassification));
            }

            // GET https://graph.microsoft.com/beta/directorySettingTemplates
            string directorySettingTemplatesUrl  = $"{GraphHttpClient.GetGraphEndPointUrl(azureEnvironment,true)}directorySettingTemplates";
            var    directorySettingTemplatesJson = GraphHttpClient.MakeGetRequestForString(directorySettingTemplatesUrl, accessToken);
            var    directorySettingTemplates     = JsonConvert.DeserializeObject <DirectorySettingTemplates>(directorySettingTemplatesJson);

            // Retrieve the setinngs for "Group.Unified"
            var unifiedGroupSetting = directorySettingTemplates.Templates.FirstOrDefault(t => t.DisplayName == "Group.Unified");

            if (unifiedGroupSetting != null)
            {
                var directorySettingValues = new Dictionary <string, string>();
                foreach (var v in unifiedGroupSetting.SettingValues)
                {
                    switch (v.Name)
                    {
                    case "UsageGuidelinesUrl":
                        directorySettingValues.Add(v.Name, usageGuidelinesUrl);
                        break;

                    case "ClassificationList":
                        directorySettingValues.Add(v.Name, classificationsList.Aggregate((s, i) => s + ", " + i));
                        break;

                    case "DefaultClassification":
                        directorySettingValues.Add(v.Name, defaultClassification);
                        break;

                    default:
                        directorySettingValues.Add(v.Name, v.DefaultValue);
                        break;
                    }
                }

                // POST https://graph.microsoft.com/beta/settings
                string newDirectorySettingUrl    = $"{GraphHttpClient.GetGraphEndPointUrl(azureEnvironment,true)}settings";
                var    newDirectorySettingResult = GraphHttpClient.MakePostRequestForString(
                    newDirectorySettingUrl,
                    content: new
                {
                    templateId = unifiedGroupSetting.Id,
                    values     = from v in directorySettingValues select new { name = v.Key, value = v.Value },
                },
                    contentType: "application/json",
                    accessToken: accessToken);
            }
            else
            {
                throw new ApplicationException("Missing DirectorySettingTemplate for \"Group.Unified\"");
            }
        }
Пример #5
0
        /// <summary>
        /// Updates Site Classifications settings for the target tenant
        /// </summary>
        /// <param name="accessToken">The OAuth accessToken for Microsoft Graph with Azure AD</param>
        /// <param name="classificationsList">The list of classification values</param>
        /// <param name="defaultClassification">The default classification</param>
        /// <param name="usageGuidelinesUrl">The URL of a guidance page</param>
        /// <param name="azureEnvironment">Defines the Azure Cloud Deployment. This is used to determine the MS Graph EndPoint to call which differs per Azure Cloud deployments. Defaults to Production (graph.microsoft.com).</param>
        public static void UpdateSiteClassificationsSettings(string accessToken, IEnumerable <string> classificationsList = null, string defaultClassification = "", string usageGuidelinesUrl = "", AzureEnvironment azureEnvironment = AzureEnvironment.Production)
        {
            if (string.IsNullOrEmpty(accessToken))
            {
                throw new ArgumentException("Specify a valid accesstoken", nameof(accessToken));
            }
            // GET https://graph.microsoft.com/beta/settings
            string directorySettingsUrl  = $"{GraphHttpClient.GetGraphEndPointUrl(azureEnvironment,true)}settings";
            var    directorySettingsJson = GraphHttpClient.MakeGetRequestForString(directorySettingsUrl, accessToken);
            var    directorySettings     = JsonConvert.DeserializeObject <DirectorySettingTemplates>(directorySettingsJson);

            // Retrieve the setinngs for "Group.Unified"
            var unifiedGroupSetting = directorySettings.Templates.FirstOrDefault(t => t.DisplayName == "Group.Unified");

            if (unifiedGroupSetting != null)
            {
                foreach (var v in unifiedGroupSetting.SettingValues)
                {
                    switch (v.Name)
                    {
                    case "UsageGuidelinesUrl":
                        if (usageGuidelinesUrl != null)
                        {
                            v.Value = usageGuidelinesUrl;
                        }
                        break;

                    case "ClassificationList":
                        if (classificationsList != null && classificationsList.Any())
                        {
                            v.Value = classificationsList.Aggregate((s, i) => s + ", " + i);
                        }
                        break;

                    case "DefaultClassification":
                        if (usageGuidelinesUrl != null)
                        {
                            v.Value = defaultClassification;
                        }
                        break;

                    default:
                        break;
                    }
                }

                // PATCH https://graph.microsoft.com/beta/settings
                string updateDirectorySettingUrl    = $"{GraphHttpClient.GetGraphEndPointUrl(azureEnvironment, true)}settings/{unifiedGroupSetting.Id}";
                var    updateDirectorySettingResult = GraphHttpClient.MakePatchRequestForString(
                    updateDirectorySettingUrl,
                    content: new
                {
                    templateId = unifiedGroupSetting.Id,
                    values     = from v in unifiedGroupSetting.SettingValues select new { name = v.Name, value = v.Value },
                },
                    contentType: "application/json",
                    accessToken: accessToken);
            }
            else
            {
                throw new ApplicationException("Missing DirectorySetting for \"Group.Unified\"");
            }
        }
Пример #6
0
        /// <summary>
        /// Returns the users delta in the current domain filtered out with a custom OData filter. If no <paramref name="deltaToken"/> has been provided, all users will be returned with a deltatoken for a next run. If a <paramref name="deltaToken"/> has been provided, all users which were modified after the deltatoken has been generated will be returned.
        /// </summary>
        /// <param name="accessToken">The OAuth 2.0 Access Token to use for invoking the Microsoft Graph</param>
        /// <param name="deltaToken">DeltaToken to indicate requesting changes since this deltatoken has been created. Leave NULL to retrieve all users with a deltatoken to use for subsequent queries.</param>
        /// <param name="filter">OData filter to apply to retrieval of the users from the Microsoft Graph</param>
        /// <param name="orderby">OData orderby instruction</param>
        /// <param name="selectProperties">Allows providing the names of properties to return regarding the users. If not provided, the standard properties will be returned.</param>
        /// <param name="startIndex">First item in the results returned by Microsoft Graph to return</param>
        /// <param name="endIndex">Last item in the results returned by Microsoft Graph to return</param>
        /// <param name="retryCount">Number of times to retry the request in case of throttling</param>
        /// <param name="delay">Milliseconds to wait before retrying the request. The delay will be increased (doubled) every retry.</param>
        /// <returns>List with User objects</returns>
        public static Model.UserDelta ListUserDelta(string accessToken, string deltaToken, string filter, string orderby, string[] selectProperties = null, int startIndex = 0, int endIndex = 999, int retryCount = 10, int delay = 500)
        {
            if (String.IsNullOrEmpty(accessToken))
            {
                throw new ArgumentNullException(nameof(accessToken));
            }

            Model.UserDelta userDelta = new Model.UserDelta
            {
                Users = new List <Model.User>()
            };
            try
            {
                // GET https://graph.microsoft.com/v1.0/users/delta
                string getUserDeltaUrl = $"{GraphHttpClient.MicrosoftGraphV1BaseUri}users/delta?";

                if (selectProperties != null)
                {
                    getUserDeltaUrl += $"$select={string.Join(",", selectProperties)}&";
                }
                if (!string.IsNullOrEmpty(filter))
                {
                    getUserDeltaUrl += $"$filter={filter}&";
                }
                if (!string.IsNullOrEmpty(deltaToken))
                {
                    getUserDeltaUrl += $"$deltatoken={deltaToken}&";
                }
                if (!string.IsNullOrEmpty(orderby))
                {
                    getUserDeltaUrl += $"$orderby={orderby}&";
                }

                getUserDeltaUrl = getUserDeltaUrl.TrimEnd('&').TrimEnd('?');

                int currentIndex = 0;

                while (true)
                {
                    var response = GraphHttpClient.MakeGetRequestForString(
                        requestUrl: getUserDeltaUrl,
                        accessToken: accessToken);

                    var userDeltaResponse = JsonConvert.DeserializeObject <Model.UserDelta>(response);

                    if (!string.IsNullOrEmpty(userDeltaResponse.DeltaToken))
                    {
                        userDelta.DeltaToken = HttpUtility.ParseQueryString(new Uri(userDeltaResponse.DeltaToken).Query).Get("$deltatoken");
                    }

                    foreach (var user in userDeltaResponse.Users)
                    {
                        currentIndex++;

                        if (currentIndex >= startIndex && currentIndex <= endIndex)
                        {
                            userDelta.Users.Add(user);
                        }
                    }

                    if (userDeltaResponse.NextLink != null && currentIndex < endIndex)
                    {
                        getUserDeltaUrl = userDeltaResponse.NextLink;
                    }
                    else
                    {
                        break;
                    }
                }
            }
            catch (ServiceException ex)
            {
                Log.Error(Constants.LOGGING_SOURCE, CoreResources.GraphExtensions_ErrorOccured, ex.Error.Message);
                throw;
            }
            return(userDelta);
        }