Exemple #1
0
        private static Boolean UserIsAdmin(String targetRole)
        {
            try
            {
                // Retrieve (using the Microsoft Graph) the current user's roles
                String jsonResponse = HttpHelper.MakeGetRequestForString(
                    String.Format("{0}me/memberOf?$select=id,displayName",
                                  MicrosoftGraphConstants.MicrosoftGraphV1BaseUri),
                    MicrosoftGraphHelper.GetAccessTokenForCurrentUser(MicrosoftGraphConstants.MicrosoftGraphResourceId));

                if (jsonResponse != null)
                {
                    var result = JsonConvert.DeserializeObject <UserRoles>(jsonResponse);
                    // Check if the requested role (of type DirectoryRole) is included in the list
                    return(result.Roles.Any(r => r.DisplayName == targetRole &&
                                            r.DataType.Equals("#microsoft.graph.directoryRole", StringComparison.InvariantCultureIgnoreCase)));
                }
            }
            catch (Exception)
            {
                // Ignore any exception and return false (user is not member of ...)
            }

            return(false);
        }
        public static GraphServiceClient GetNewGraphClient(string accessToken = null)
        {
            var client = new GraphServiceClient(
                new DelegateAuthenticationProvider(
                    (requestMessage) =>
            {
                if (String.IsNullOrEmpty(accessToken))
                {
                    // Get back the access token.
                    accessToken = MicrosoftGraphHelper.GetAccessTokenForCurrentUser();
                }

                if (!String.IsNullOrEmpty(accessToken))
                {
                    // Configure the HTTP bearer Authorization Header
                    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                }
                else
                {
                    throw new Exception("Invalid authorization context");
                }

                return(Task.FromResult(0));
            }
                    )
                );

            return(client);
        }