Ejemplo n.º 1
0
        /// <summary>
        /// Checks that a SharePoint client is available to the client.
        /// </summary>
        /// <returns>The SharePoint Online client.</returns>
        public static async Task <SharePointClient> EnsureSharePointClientCreatedAsync()
        {
            try
            {
                AuthenticationContext = new AuthenticationContext(CommonAuthority);

                if (AuthenticationContext.TokenCache.ReadItems().Count() > 0)
                {
                    // Bind the AuthenticationContext to the authority that sourced the token in the cache
                    // this is needed for the cache to work when asking for a token from that authority
                    // (the common endpoint never triggers cache hits)
                    string cachedAuthority = AuthenticationContext.TokenCache.ReadItems().First().Authority;
                    AuthenticationContext = new AuthenticationContext(cachedAuthority);
                }

                // Create a DiscoveryClient using the discovery endpoint Uri.
                DiscoveryClient discovery = new DiscoveryClient(DiscoveryServiceEndpointUri,
                                                                async() => await AcquireTokenAsync(AuthenticationContext, DiscoveryResourceId));

                // Now get the capability that you are interested in.
                CapabilityDiscoveryResult result = await discovery.DiscoverCapabilityAsync("MyFiles");

                var client = new SharePointClient(
                    result.ServiceEndpointUri,
                    async() => await AcquireTokenAsync(AuthenticationContext, result.ServiceResourceId));

                return(client);
            }
            catch (DiscoveryFailedException dfe)
            {
                MessageDialogHelper.DisplayException(dfe as Exception);

                // Discovery failed.
                AuthenticationContext.TokenCache.Clear();
                return(null);
            }
            catch (MissingConfigurationValueException mcve)
            {
                MessageDialogHelper.DisplayException(mcve);

                // Connected services not added correctly, or permissions not set correctly.
                AuthenticationContext.TokenCache.Clear();
                return(null);
            }
            catch (AuthenticationFailedException afe)
            {
                MessageDialogHelper.DisplayException(afe);

                // Failed to authenticate the user
                AuthenticationContext.TokenCache.Clear();
                return(null);
            }
            catch (ArgumentException ae)
            {
                MessageDialogHelper.DisplayException(ae as Exception);
                // Argument exception
                AuthenticationContext.TokenCache.Clear();
                return(null);
            }
        }
Ejemplo n.º 2
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            Uri spSiteUri;

            try
            {
                //Validate that the input is at least a well-formed URI
                spSiteUri = new Uri(spSite.Text);

                await AuthenticationHelper.EnsureAccessTokenAvailableAsync(spSiteUri.AbsoluteUri);

                this.Frame.Navigate(typeof(ItemsPage));
            }
            catch (FormatException fe)
            {
                // Tell the user that the authentication failed
                MessageDialogHelper.DisplayException(fe);
                return;
            }
            catch (AuthenticationFailedException afe)
            {
                // Tell the user that the authentication failed
                MessageDialogHelper.DisplayException(afe);
                return;
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Checks that an OutlookServicesClient object is available.
        /// </summary>
        /// <returns>The OutlookServicesClient object. </returns>
        public static async Task <OutlookServicesClient> EnsureOutlookClientCreatedAsync(string capability)
        {
            //Check to see if this client has already been created. If so, return it. Otherwise, create a new one.
            if (_outlookClient != null)
            {
                return(_outlookClient);
            }
            else
            {
                try
                {
                    // Now get the capability that you are interested in.
                    CapabilityDiscoveryResult result = await GetDiscoveryCapabilityResultAsync(capability);

                    _outlookClient = new OutlookServicesClient(
                        result.ServiceEndpointUri,
                        async() => await GetTokenHelperAsync(_authenticationContext, result.ServiceResourceId));

                    return(_outlookClient);
                }
                // The following is a list of all exceptions you should consider handling in your app.
                // In the case of this sample, the exceptions are handled by returning null upstream.
                catch (DiscoveryFailedException dfe)
                {
                    MessageDialogHelper.DisplayException(dfe as Exception);

                    // Discovery failed.
                    _authenticationContext.TokenCache.Clear();
                    return(null);
                }
                catch (MissingConfigurationValueException mcve)
                {
                    MessageDialogHelper.DisplayException(mcve);

                    // Connected services not added correctly, or permissions not set correctly.
                    _authenticationContext.TokenCache.Clear();
                    return(null);
                }
                catch (AuthenticationFailedException afe)
                {
                    MessageDialogHelper.DisplayException(afe);

                    // Failed to authenticate the user
                    _authenticationContext.TokenCache.Clear();
                    return(null);
                }
                catch (ArgumentException ae)
                {
                    MessageDialogHelper.DisplayException(ae as Exception);
                    // Argument exception
                    _authenticationContext.TokenCache.Clear();
                    return(null);
                }
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Checks that a SharePoint client is available to the client.
        /// </summary>
        /// <returns>The SharePoint Online client.</returns>
        public static async Task <SharePointClient> EnsureSharePointClientCreatedAsync()
        {
            //Check to see if this client has already been created. If so, return it. Otherwise, create a new one.
            if (_sharePointClient != null)
            {
                return(_sharePointClient);
            }
            else
            {
                try
                {
                    // Now get the capability that you are interested in.
                    CapabilityDiscoveryResult result = await GetDiscoveryCapabilityResultAsync("MyFiles");

                    _sharePointClient = new SharePointClient(
                        result.ServiceEndpointUri,
                        async() => await GetTokenHelperAsync(_authenticationContext, result.ServiceResourceId));

                    return(_sharePointClient);
                }
                catch (DiscoveryFailedException dfe)
                {
                    MessageDialogHelper.DisplayException(dfe as Exception);

                    // Discovery failed.
                    _authenticationContext.TokenCache.Clear();
                    return(null);
                }
                catch (MissingConfigurationValueException mcve)
                {
                    MessageDialogHelper.DisplayException(mcve);

                    // Connected services not added correctly, or permissions not set correctly.
                    _authenticationContext.TokenCache.Clear();
                    return(null);
                }
                catch (AuthenticationFailedException afe)
                {
                    MessageDialogHelper.DisplayException(afe);

                    // Failed to authenticate the user
                    _authenticationContext.TokenCache.Clear();
                    return(null);
                }
                catch (ArgumentException ae)
                {
                    MessageDialogHelper.DisplayException(ae as Exception);
                    // Argument exception
                    _authenticationContext.TokenCache.Clear();
                    return(null);
                }
            }
        }
        private async void sendRequest_Click(object sender, RoutedEventArgs e)
        {
            // The access token may have expired.
            // By calling the EnsureAccessTokenAvailableAsync we ensure that it is still valid,
            // or we can get another one.
            await AuthenticationHelper.EnsureAccessTokenAvailableAsync();

            try
            {
                // Update the headers data source
                BindingExpression headersBindingExpression = requestHeadersText.GetBindingExpression(TextBox.TextProperty);
                headersBindingExpression.UpdateSource();
            }
            catch (Exception ex)
            {
                // The headers data is not a well-formed JSON string
                FormatException fe = new FormatException(ex.Message);
                MessageDialogHelper.DisplayException(fe);
                return;
            }
            try
            {
                // Update the body data source
                BindingExpression bodyBindingExpression = requestBodyText.GetBindingExpression(TextBox.TextProperty);
                bodyBindingExpression.UpdateSource();
            }
            catch (Exception ex)
            {
                InvalidOperationException ioe = new InvalidOperationException(ex.Message);
                MessageDialogHelper.DisplayException(ioe);
                return;
            }


            // There are no errors that stop us from sending the request.
            // Create a new response item and assign it to the current item in the data source
            var selectedItem = (DataItem)itemsViewSource.View.CurrentItem;

            selectedItem.Response = await DataSource.GetResponseAsync(selectedItem.Request);

            // Show the Response UI
            VisualStateManager.GoToState(this, "ResponseView", true);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Checks that a Graph client is available.
        /// </summary>
        /// <returns>The Graph client.</returns>
        public static async Task <ActiveDirectoryClient> EnsureGraphClientCreatedAsync()
        {
            // Active Directory service endpoints
            const string AadServiceResourceId  = "https://graph.windows.net/";
            Uri          AadServiceEndpointUri = new Uri("https://graph.windows.net/");

            try
            {
                AuthenticationContext = new AuthenticationContext(CommonAuthority);

                TokenCacheItem cacheItem = null;

                if (AuthenticationContext.TokenCache.ReadItems().Count() > 0)
                {
                    // Bind the AuthenticationContext to the authority that sourced the token in the cache
                    // this is needed for the cache to work when asking for a token from that authority
                    // (the common endpoint never triggers cache hits)
                    cacheItem             = AuthenticationContext.TokenCache.ReadItems().First();
                    AuthenticationContext = new AuthenticationContext(cacheItem.Authority);
                }
                else
                {
                    // Nothing was found in the cache, so let's acquire a token.
                    var token = await AcquireTokenAsync(AuthenticationContext, AadServiceResourceId);

                    // Check the token
                    if (String.IsNullOrEmpty(token))
                    {
                        // User cancelled sign-in
                        return(null);
                    }
                    else
                    {
                        // If a token was acquired, the TokenCache will contain a TokenCacheItem containing
                        // all the details of the authorization.
                        cacheItem = AuthenticationContext.TokenCache.ReadItems().First();
                    }
                }

                // Store the Id of the logged-in user so that we can retrieve more user info later.
                _loggedInUser = cacheItem.UniqueId;

                // Create our ActiveDirectory client.
                var client = new ActiveDirectoryClient(
                    new Uri(AadServiceEndpointUri, cacheItem.TenantId),
                    async() => await AcquireTokenAsync(AuthenticationContext, AadServiceResourceId));

                return(client);
            }
            // The following is a list of all exceptions you should consider handling in your app.
            // In the case of this sample, the exceptions are handled by returning null upstream.
            catch (DiscoveryFailedException dfe)
            {
                MessageDialogHelper.DisplayException(dfe as Exception);

                // Discovery failed.
                AuthenticationContext.TokenCache.Clear();
                return(null);
            }
            catch (MissingConfigurationValueException mcve)
            {
                MessageDialogHelper.DisplayException(mcve);

                // Connected services not added correctly, or permissions not set correctly.
                AuthenticationContext.TokenCache.Clear();
                return(null);
            }
            catch (AuthenticationFailedException afe)
            {
                MessageDialogHelper.DisplayException(afe);

                // Failed to authenticate the user
                AuthenticationContext.TokenCache.Clear();
                return(null);
            }
            catch (ArgumentException ae)
            {
                MessageDialogHelper.DisplayException(ae as Exception);

                // Argument exception
                AuthenticationContext.TokenCache.Clear();
                return(null);
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Checks that a Graph client is available.
        /// </summary>
        /// <returns>The Graph client.</returns>
        public static async Task <ActiveDirectoryClient> EnsureGraphClientCreatedAsync()
        {
            //Check to see if this client has already been created. If so, return it. Otherwise, create a new one.
            if (_graphClient != null)
            {
                return(_graphClient);
            }
            else
            {
                // Active Directory service endpoints
                const string AadServiceResourceId  = "https://graph.windows.net/";
                Uri          AadServiceEndpointUri = new Uri("https://graph.windows.net/");

                try
                {
                    //First, look for the authority used during the last authentication.
                    //If that value is not populated, use CommonAuthority.
                    string authority = null;
                    if (String.IsNullOrEmpty(LastAuthority))
                    {
                        authority = CommonAuthority;
                    }
                    else
                    {
                        authority = LastAuthority;
                    }

                    // Create an AuthenticationContext using this authority.
                    _authenticationContext = new AuthenticationContext(authority);

                    // Set the value of _authenticationContext.UseCorporateNetwork to true so that you
                    // can use this app inside a corporate intranet. If the value of UseCorporateNetwork
                    // is true, you also need to add the Enterprise Authentication, Private Networks, and
                    // Shared User Certificates capabilities in the Package.appxmanifest file.
                    _authenticationContext.UseCorporateNetwork = true;

                    var token = await GetTokenHelperAsync(_authenticationContext, AadServiceResourceId);

                    // Check the token
                    if (String.IsNullOrEmpty(token))
                    {
                        // User cancelled sign-in
                        return(null);
                    }
                    else
                    {
                        // Create our ActiveDirectory client.
                        _graphClient = new ActiveDirectoryClient(
                            new Uri(AadServiceEndpointUri, TenantId),
                            async() => await GetTokenHelperAsync(_authenticationContext, AadServiceResourceId));

                        return(_graphClient);
                    }
                }

                catch (Exception e)
                {
                    MessageDialogHelper.DisplayException(e as Exception);

                    // Argument exception
                    _authenticationContext.TokenCache.Clear();
                    return(null);
                }
            }
        }