private async Task <OutlookServicesClient> EnsureClientCreated()
        {
            // fetch from stuff user claims
            var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            var userObjectId = ClaimsPrincipal.Current.FindFirst(SettingsHelper.ClaimTypeObjectIdentifier).Value;

            // discover contact endpoint
            var clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
            var userIdentifier   = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);

            // create auth context
            AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, new EFADALTokenCache(signInUserId));

            // create O365 discovery client
            DiscoveryClient discovery = new DiscoveryClient(new Uri(SettingsHelper.O365DiscoveryServiceEndpoint),
                                                            async() => {
                var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.O365DiscoveryResourceId, clientCredential, userIdentifier);

                return(authResult.AccessToken);
            });

            // query discovery service for endpoint for 'calendar' endpoint
            CapabilityDiscoveryResult dcr = await discovery.DiscoverCapabilityAsync("Contacts");

            // create an OutlookServicesclient
            return(new OutlookServicesClient(dcr.ServiceEndpointUri,
                                             async() => {
                var authResult =
                    await
                    authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId, clientCredential, userIdentifier);
                return authResult.AccessToken;
            }));
        }
示例#2
0
        public static async Task <CapabilityDiscoveryResult> GetDiscoveryCapabilityResultAsync(string capability)
        {
            var cacheResult = await DiscoveryServiceCache.LoadAsync();

            CapabilityDiscoveryResult discoveryCapabilityResult = null;

            if (cacheResult != null && cacheResult.DiscoveryInfoForServices.ContainsKey(capability))
            {
                discoveryCapabilityResult = cacheResult.DiscoveryInfoForServices[capability];

                if (LoggedInUser != cacheResult.UserId)
                {
                    // cache is for another user
                    cacheResult = null;
                }
            }

            if (cacheResult == null)
            {
                cacheResult = await CreateAndSaveDiscoveryServiceCacheAsync();

                discoveryCapabilityResult = cacheResult.DiscoveryInfoForServices[capability];
            }

            return(discoveryCapabilityResult);
        }
示例#3
0
        public static async Task <CapabilityDiscoveryResult> GetDiscoveryCapabilityResultAsync(string capability)
        {
            var cacheResult = await DiscoveryServiceCache.LoadAsync();

            CapabilityDiscoveryResult discoveryCapabilityResult = null;

            if (cacheResult != null && cacheResult.DiscoveryInfoForServices.ContainsKey(capability))
            {
                discoveryCapabilityResult = cacheResult.DiscoveryInfoForServices[capability];

                if (LoggedInUser != cacheResult.UserId)
                {
                    // cache is for another user
                    cacheResult = null;
                }
            }

            //Cache might exist from previous calls, but it might not include newly added capabilities.
            else if (cacheResult != null && !cacheResult.DiscoveryInfoForServices.ContainsKey(capability))
            {
                cacheResult = null;
                cacheResult = await CreateAndSaveDiscoveryServiceCacheAsync();

                discoveryCapabilityResult = cacheResult.DiscoveryInfoForServices[capability];
            }

            if (cacheResult == null)
            {
                cacheResult = await CreateAndSaveDiscoveryServiceCacheAsync();

                discoveryCapabilityResult = cacheResult.DiscoveryInfoForServices[capability];
            }

            return(discoveryCapabilityResult);
        }
        private async void btnDiscoverContacts_Click(object sender, RoutedEventArgs e)
        {
            String discoveryResultText = "Capability: {0} \nEndpoint Uri: {1} \nResource Id: {2}\n\n";

            var capabilityContacts = ServiceCapabilities.Contacts.ToString();

            CapabilityDiscoveryResult discoveryCapabilityResult = await Office365ServiceHelper.GetDiscoveryCapabilityResultAsync(capabilityContacts);

            txtBoxStatus.Text = String.Format(discoveryResultText,
                                              capabilityContacts,
                                              discoveryCapabilityResult.ServiceEndpointUri.ToString(),
                                              discoveryCapabilityResult.ServiceResourceId).Replace("\n", Environment.NewLine);

            OutlookServicesClient outlookContactsClient = new OutlookServicesClient(discoveryCapabilityResult.ServiceEndpointUri,
                                                                                    async() =>
            {
                return(await Office365ServiceHelper.GetAccessTokenForResourceAsync(discoveryCapabilityResult));
            });

            var contactsResults = await outlookContactsClient.Me.Contacts.ExecuteAsync();

            do
            {
                var contacts = contactsResults.CurrentPage;
                foreach (var contact in contacts)
                {
                    txtBoxStatus.Text += String.Format(discoveryResultText,
                                                       capabilityContacts,
                                                       contact.DisplayName,
                                                       contact.JobTitle).Replace("\n", Environment.NewLine);
                }

                contactsResults = await contactsResults.GetNextPageAsync();
            } while (contactsResults != null);
        }
示例#5
0
      private void comboBox1_SelectedIndexChanged( object sender, EventArgs e )
      {

         _selectedService = comboBox1.SelectedValue as CapabilityDiscoveryResult;
         if ( _selectedService != null )
         {
            string resourceId = _selectedService.ServiceResourceId;
            _selectedApiEnpoint = _selectedService.ServiceEndpointUri.AbsoluteUri;

            if ( comboBox1.Text.Equals( "SharePoint", StringComparison.OrdinalIgnoreCase ) )
            {
               GetSharePointEnpoint( resourceId );
            }
            if ( comboBox1.Text.Equals( "OneDrive", StringComparison.OrdinalIgnoreCase ) )
            {
               _selectedApiEnpoint = _selectedApiEnpoint.Replace( "v1.0", "v2.0" ).Replace( "/me", "" );
            }
            _selectedResourceAuthResult = Program.authContext.AcquireToken(
                  resourceId,
                  SiteSettings.ClientId,
                  new Uri( SiteSettings.RedirectUrl ) );

            lblServiceInfoOutput.Text = $"Selected Resource:   {resourceId}\r\n"
                                          + $"Selected Endpoint:   {_selectedApiEnpoint}\r\n"
                                          + $"User:                {_selectedResourceAuthResult.UserInfo.DisplayableId}";

         }
      }
示例#6
0
        public static async Task <List <string> > GetListItems(string listName)
        {
            // Use the discovery service to get the URL of the root site and an access token to talk to it.
            string accessToken = await GetAccessTokenForResource("https://api.office.com/discovery/");

            DiscoveryClient           discoveryClient = new DiscoveryClient(() => accessToken);
            CapabilityDiscoveryResult result          = await discoveryClient.DiscoverCapabilityAsync("RootSite");

            var sharePointAccessToken = await GetAccessTokenForResource(result.ServiceResourceId);

            var sharePointServiceEndpointUri = result.ServiceEndpointUri.ToString();

            // Construct an HTTP request to bring back te contents of the Announcements list in the root site.
            string             url     = string.Format("{0}/web/lists/GetByTitle('{1}')/items", sharePointServiceEndpointUri, listName);
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, new Uri(url));

            request.Headers.Add("Accept", "text/xml");

            // Bring back the list of announcements
            HttpClient client = new HttpClient();

            client.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("Bearer", sharePointAccessToken);
            var response = await client.SendRequestAsync(request);

            // Quick fix to bring back just the titles - would need to be parsed properly in a real app!
            XElement   reponseAsXml = XElement.Parse(response.Content.ToString());
            XNamespace dNameSpace   = "http://schemas.microsoft.com/ado/2007/08/dataservices";

            return(reponseAsXml.Descendants(dNameSpace + "Title")
                   .Select(x => (string)x)
                   .ToList());
        }
示例#7
0
        private static async Task <SharePointClient> GetSharePointClient()
        {
            string signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            string userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
            string tenantId     = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

            AuthenticationContext authContext = new AuthenticationContext(string.Format("{0}/{1}", SettingsHelper.AuthorizationUri, tenantId), new ADALTokenCache(signInUserId));

            DiscoveryClient discovery = new DiscoveryClient(SettingsHelper.DiscoveryServiceEndpointUri,
                                                            async() =>
            {
                var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.DiscoveryServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                return(authResult.AccessToken);
            });

            CapabilityDiscoveryResult capability = await discovery.DiscoverCapabilityAsync(SettingsHelper.Capability);

            SharePointClient client = new SharePointClient(capability.ServiceEndpointUri,
                                                           async() =>
            {
                var authResult = await authContext.AcquireTokenSilentAsync(capability.ServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                return(authResult.AccessToken);
            });

            return(client);
        }
示例#8
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);
            }
        }
示例#9
0
        public static async Task <CapabilityDiscoveryResult> GetDiscoveryCapabilityResultAsync(string capability)
        {
            var cacheResult = await DiscoveryServiceCache.LoadAsync();

            CapabilityDiscoveryResult discoveryCapabilityResult = null;

            if (cacheResult != null && cacheResult.DiscoveryInfoForServices.ContainsKey(capability))
            {
                discoveryCapabilityResult = cacheResult.DiscoveryInfoForServices[capability];

                var initialAuthResult = await GetAccessTokenAsync(discoveryCapabilityResult.ServiceResourceId);

                if (initialAuthResult.UserInfo.UniqueId != cacheResult.UserId)
                {
                    // cache is for another user
                    cacheResult = null;
                }
            }

            if (cacheResult == null)
            {
                cacheResult = await CreateAndSaveDiscoveryServiceCacheAsync();

                discoveryCapabilityResult = cacheResult.DiscoveryInfoForServices[capability];
            }

            return(discoveryCapabilityResult);
        }
示例#10
0
        private void GetService(string capability, out Uri serviceEndpointUri, out string serviceResourceId)
        {
            var discoveryClient = new DiscoveryClient(DiscoveryServiceEndpointUri,
                                                      async() => await AuthenticationHelperSDK.GetTokenAsync(DiscoveryResourceId));

            CapabilityDiscoveryResult result = discoveryClient.DiscoverCapabilityAsync(capability).Result;

            serviceEndpointUri = result.ServiceEndpointUri;
            serviceResourceId  = result.ServiceResourceId;
        }
示例#11
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);
                }
            }
        }
示例#12
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);
                }
            }
        }
示例#13
0
        private static async Task <SharePointClient> EnsureClient()
        {
            DiscoveryClient discoveryClient = new DiscoveryClient(
                async() => await GetAccessTokenForResource("https://api.office.com/discovery/"));

            // Get the "MyFiles" capability.
            CapabilityDiscoveryResult result = await discoveryClient.DiscoverCapabilityAsync("MyFiles");

            return(new SharePointClient(result.ServiceEndpointUri, async() => {
                return await GetAccessTokenForResource(result.ServiceResourceId);
            }));
        }
        private async void btnDiscoverMyFiles_Click(object sender, RoutedEventArgs e)
        {
            String discoveryResultText = "Capability: {0} \nEndpoint Uri: {1} \nResource Id: {2}\n\n";

            var capabilityMyFiles = ServiceCapabilities.MyFiles.ToString();

            CapabilityDiscoveryResult discoveryCapabilityResult = await Office365ServiceHelper.GetDiscoveryCapabilityResultAsync(capabilityMyFiles);

            txtBoxStatus.Text = String.Format(discoveryResultText,
                                              capabilityMyFiles,
                                              discoveryCapabilityResult.ServiceEndpointUri.ToString(),
                                              discoveryCapabilityResult.ServiceResourceId).Replace("\n", Environment.NewLine);
        }
        private static async Task ExecuteSearchQuery(List <SearchResult> results, CapabilityDiscoveryResult dcr, string sharePointToken, string query)
        {
            HttpClient client = new HttpClient();

            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + sharePointToken);
            client.DefaultRequestHeaders.Add("Accept", "application/json; odata=verbose");
            using (HttpResponseMessage response = await client.GetAsync(new Uri(dcr.ServiceEndpointUri + query, UriKind.Absolute)))
            {
                if (response.IsSuccessStatusCode)
                {
                    XElement root  = SearchModel.Json2Xml(await response.Content.ReadAsStringAsync());
                    var      items = root.Descendants("RelevantResults").Elements("Table").Elements("Rows").Elements("results").Elements("item");
                    foreach (var item in items)
                    {
                        //loop through the properties returned for this item
                        var newItem = new SearchResult();
                        foreach (var prop in item.Descendants("item"))
                        {
                            if (prop.Element("Key").Value == "Title")
                            {
                                newItem.Title = prop.Element("Value").Value;
                            }
                            else if (prop.Element("Key").Value == "Path")
                            {
                                newItem.Path = prop.Element("Value").Value;
                            }
                            else if (prop.Element("Key").Value == "SiteLogo")
                            {
                                newItem.SiteLogo = prop.Element("Value").Value;
                            }
                            else if (prop.Element("Key").Value == "contentclass")
                            {
                                newItem.ContentClass = prop.Element("Value").Value;
                            }
                        }

                        //only return site collections in primary domain...not the onedrive or public domains
                        //this would probably be better placed in the original search query
                        if (newItem.Path.ToLower().Contains(dcr.ServiceResourceId.ToLower()))
                        {
                            results.Add(newItem);
                        }
                    }
                }
            }
        }
示例#16
0
        public static async Task <ServiceCapabilityCache> LoadAsync(ServiceCapabilities capability)
        {
            CapabilityDiscoveryResult capabilityDiscoveryResult = null;

            DiscoveryServiceCache cache = await LoadAsync();

            cache.DiscoveryInfoForServices.TryGetValue(capability.ToString(), out capabilityDiscoveryResult);

            if (cache == null || capabilityDiscoveryResult == null)
            {
                return(null);
            }

            return(new ServiceCapabilityCache
            {
                UserId = cache.UserId,
                CapabilityResult = capabilityDiscoveryResult
            });
        }
        /// <summary>
        /// Checks that an OutlookServicesClient object is available.
        /// </summary>
        /// <returns>The OutlookServicesClient object. </returns>
        public static async Task <OutlookServicesClient> GetOutlookClientAsync(string capability)
        {
            if (_outlookClient != null)
            {
                return(_outlookClient);
            }
            else
            {
                try
                {
                    // See the Discovery Service Sample (https://github.com/OfficeDev/Office365-Discovery-Service-Sample)
                    // for an approach that improves performance by storing the discovery service information in a cache.
                    DiscoveryClient discoveryClient = new DiscoveryClient(
                        async() => await GetTokenHelperAsync(AuthenticationContext, DiscoveryResourceId));

                    // Get the specified capability ("Mail").
                    CapabilityDiscoveryResult result =
                        await discoveryClient.DiscoverCapabilityAsync(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)
                {
                    // Discovery failed.
                    Debug.WriteLine("Exception: " + dfe.Message);
                    AuthenticationContext.TokenCache.Clear();
                    return(null);
                }
                catch (ArgumentException ae)
                {
                    // Argument exception
                    Debug.WriteLine("Exception: " + ae.Message);
                    AuthenticationContext.TokenCache.Clear();
                    return(null);
                }
            }
        }
示例#18
0
        internal async Task <bool> CreateOutlookClientAsyncInternal(string capability)
        {
            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);

                DiscoveryClient discoveryClient = new DiscoveryClient(
                    async() => await GetTokenHelperAsync(_authenticationContext, DiscoveryResourceId));

                // Get the specified capability ("Calendar").
                CapabilityDiscoveryResult result =
                    await discoveryClient.DiscoverCapabilityAsync(capability);

                var client = new OutlookServicesClient(
                    result.ServiceEndpointUri,
                    async() =>
                    await GetTokenHelperAsync(_authenticationContext, result.ServiceResourceId));
                _outLookClient = client;
                return(true);
            }
            catch (Exception ex)
            {
                if (_authenticationContext != null && _authenticationContext.TokenCache != null)
                {
                    _authenticationContext.TokenCache.Clear();
                }
                _outLookClient = null;
                return(false);
            }
        }
示例#19
0
        public static async Task <CapabilityDiscoveryResult> GetCapabilityDiscoveryResultAsync(ServiceCapabilities serviceCapability)
        {
            var discoveryServiceInfo = await GetAllCapabilityDiscoveryResultAsync();

            DiscoveryServiceCache discoveryCache = null;

            var cacheResult = await DiscoveryServiceCache.LoadAsync(serviceCapability);

            if (cacheResult == null)
            {
                discoveryCache = await CreateAndSaveDiscoveryServiceCacheAsync();

                CapabilityDiscoveryResult capabilityDiscoveryResult = null;

                discoveryCache.DiscoveryInfoForServices.TryGetValue(serviceCapability.ToString(), out capabilityDiscoveryResult);

                return(capabilityDiscoveryResult);
            }
            else
            {
                return(cacheResult.CapabilityResult);
            }
        }
示例#20
0
        private async Task <string> GetSharePointServiceEndpointUri()
        {
            if (sharePointServiceEndpointUri != null)
            {
                return(sharePointServiceEndpointUri);
            }
            else
            {
                string accessToken = await GetAccessTokenForResource("https://api.office.com/discovery/");

                DiscoveryClient discoveryClient = new DiscoveryClient(() =>
                {
                    return(accessToken);
                });

                CapabilityDiscoveryResult result = await discoveryClient.DiscoverCapabilityAsync("RootSite");

                sharePointAccessToken = await GetAccessTokenForResource(result.ServiceResourceId);

                sharePointServiceEndpointUri = result.ServiceEndpointUri.ToString();

                return(sharePointServiceEndpointUri);
            }
        }
        public static async Task <string> GetTokenAsync(string capability)
        {
            CapabilityDiscoveryResult result = await GetDiscoveryCapabilityResultAsync(capability);

            return(await GetTokenHelperAsync(_authenticationContext, result.ServiceResourceId));
        }
示例#22
0
        public async Task <ActionResult> Index(string code)
        {
            List <MyEvent> eventList = new List <MyEvent>();

            AuthenticationContext authContext = new AuthenticationContext(
                ConfigurationManager.AppSettings["ida:AuthorizationUri"] + "/common",
                true);

            ClientCredential creds = new ClientCredential(
                ConfigurationManager.AppSettings["ida:ClientID"],
                ConfigurationManager.AppSettings["ida:Password"]);

            DiscoveryClient           disco       = GetFromCache("DiscoveryClient") as DiscoveryClient;
            CapabilityDiscoveryResult eventsDisco = GetFromCache("EventsDiscovery") as CapabilityDiscoveryResult;

            //Redirect to login page if we do not have an
            //authorization code for the Discovery service
            if (disco == null && code == null)
            {
                Uri redirectUri = authContext.GetAuthorizationRequestURL(
                    discoResource,
                    creds.ClientId,
                    new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
                    UserIdentifier.AnyUser,
                    string.Empty);

                return(Redirect(redirectUri.ToString()));
            }

            //Create a DiscoveryClient using the authorization code
            if (disco == null && code != null)
            {
                disco = new DiscoveryClient(new Uri(discoEndpoint), async() =>
                {
                    var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
                        code,
                        new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
                        creds);

                    return(authResult.AccessToken);
                });
            }

            if (disco != null && code != null & eventsDisco == null)
            {
                //Discover required capabilities
                eventsDisco = await disco.DiscoverCapabilityAsync("Calendar");

                SaveInCache("EventsDiscovery", eventsDisco);

                code = null;

                //Get authorization code for the calendar
                Uri redirectUri = authContext.GetAuthorizationRequestURL(
                    eventsDisco.ServiceResourceId,
                    creds.ClientId,
                    new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
                    UserIdentifier.AnyUser,
                    string.Empty);

                return(Redirect(redirectUri.ToString()));
            }

            //Get the calendar events
            if (disco != null && code != null & eventsDisco != null)
            {
                OutlookServicesClient outlookClient = new OutlookServicesClient(eventsDisco.ServiceEndpointUri, async() =>
                {
                    var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
                        code,
                        new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
                        creds);

                    return(authResult.AccessToken);
                });

                //Get the events for the next 8 hours
                var eventResults = await(from i in outlookClient.Me.Events
                                         where i.End >= DateTimeOffset.UtcNow && i.End <= DateTimeOffset.UtcNow.AddHours(8)
                                         select i).Take(5).ExecuteAsync();
                var events = eventResults.CurrentPage.OrderBy(e => e.Start);

                foreach (var e in events)
                {
                    eventList.Add(new MyEvent
                    {
                        Id       = e.Id,
                        Body     = e.Body == null ? string.Empty : e.Body.Content,
                        End      = e.End,
                        Location = e.Location == null ? string.Empty : e.Location.DisplayName,
                        Start    = e.Start,
                        Subject  = e.Subject == null ? string.Empty : e.Subject
                    });
                }

                //cache the events
                SaveInCache("Events", eventList);
            }

            return(View());
        }
示例#23
0
        // GET: Files
        public async Task <ActionResult> Index(string authError)
        {
            List <MyFile> myFiles = new List <MyFile>();

            AuthenticationContext     authContext = null;
            AuthenticationResult      result      = null;
            CapabilityDiscoveryResult filesCapabilityDiscoveryResult = null;
            DiscoveryClient           discoveryClient = null;
            SharePointClient          spClient        = null;

            string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").Value;

            ClientCredential credential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey);

            try
            {
                authContext = new AuthenticationContext(SettingsHelper.Authority, new TokenDbCache(userObjectID));

                if (authError != null)
                {
                    Uri redirectUri = new Uri(Request.Url.GetLeftPart(UriPartial.Authority).ToString() + "/OAuth");

                    string state = GenerateState(userObjectID, Request.Url.ToString());

                    ViewBag.AuthorizationUrl = authContext.GetAuthorizationRequestURL(SettingsHelper.DiscoveryServiceResourceId,
                                                                                      SettingsHelper.ClientId,
                                                                                      redirectUri,
                                                                                      UserIdentifier.AnyUser,
                                                                                      state == null ? null : "&state=" + state);

                    ViewBag.ErrorMessage = "UnexpectedError";

                    return(View(myFiles));
                }

                // Query Discovery Service to retrieve MyFiles capability result
                result          = authContext.AcquireTokenSilent(SettingsHelper.DiscoveryServiceResourceId, credential, UserIdentifier.AnyUser);
                discoveryClient = new DiscoveryClient(() =>
                {
                    return(result.AccessToken);
                });
            }
            catch (AdalException e)
            {
                if (e.ErrorCode == AdalError.FailedToAcquireTokenSilently)
                {
                    // The user needs to re-authorize.  Show them a message to that effect.
                    // If the user still has a valid session with Azure AD, they will not be prompted for their credentials.
                    ViewBag.ErrorMessage = "AuthorizationRequired";
                    authContext          = new AuthenticationContext(SettingsHelper.Authority);
                    Uri redirectUri = new Uri(Request.Url.GetLeftPart(UriPartial.Authority).ToString() + "/OAuth");

                    string state = GenerateState(userObjectID, Request.Url.ToString());

                    ViewBag.AuthorizationUrl = authContext.GetAuthorizationRequestURL(SettingsHelper.DiscoveryServiceResourceId,
                                                                                      SettingsHelper.ClientId,
                                                                                      redirectUri,
                                                                                      UserIdentifier.AnyUser,
                                                                                      state == null ? null : "&state=" + state);

                    return(View(myFiles));
                }

                ViewBag.ErrorMessage = "Error while Acquiring Token from Cache.";

                return(View("Error"));
            }

            try
            {
                ViewBag.Office365User = result.UserInfo.GivenName;

                ActiveDirectoryClient adGraphClient = new ActiveDirectoryClient(SettingsHelper.AADGraphServiceEndpointUri,
                                                                                async() =>
                {
                    var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.AADGraphResourceId, credential, UserIdentifier.AnyUser);

                    return(authResult.AccessToken);
                });

                var currentUser = await adGraphClient.Users.Where(u => u.ObjectId == result.UserInfo.UniqueId).ExecuteSingleAsync();

                ViewBag.Office365User = String.Format("{0} ({1})", currentUser.DisplayName, currentUser.Mail);

                filesCapabilityDiscoveryResult = await discoveryClient.DiscoverCapabilityAsync("MyFiles");

                // Initialize SharePoint client to query users' files
                spClient = new SharePointClient(filesCapabilityDiscoveryResult.ServiceEndpointUri,
                                                async() =>
                {
                    var authResult = await authContext.AcquireTokenSilentAsync(filesCapabilityDiscoveryResult.ServiceResourceId, credential, UserIdentifier.AnyUser);

                    return(authResult.AccessToken);
                });

                // Query users' files and get the first paged collection
                var filesCollection = await spClient.Files.ExecuteAsync();

                var files = filesCollection.CurrentPage;
                foreach (var file in files)
                {
                    myFiles.Add(new MyFile {
                        Name = file.Name
                    });
                }

                return(View(myFiles));
            }
            catch (Exception e)
            {
                ViewBag.ErrorMessage = String.Format("UnexpectedError: {0}", e.Message);

                return(View("Error"));
            }
        }
示例#24
0
        /// <summary>
        /// Use the DiscoveryClient to get the Contacts and Files endpoints
        /// </summary>
        /// <param name="code">The authorization code to use when getting an access token</param>
        /// <returns></returns>
        public async Task <ActionResult> Index(string code)
        {
            AuthenticationContext authContext = new AuthenticationContext(
                ConfigurationManager.AppSettings["ida:AuthorizationUri"] + "/common",
                true);

            ClientCredential creds = new ClientCredential(
                ConfigurationManager.AppSettings["ida:ClientID"],
                ConfigurationManager.AppSettings["ida:Password"]);

            DiscoveryClient disco = Helpers.GetFromCache("DiscoveryClient") as DiscoveryClient;

            //Redirect to login page if we do not have an
            //authorization code for the Discovery service
            if (disco == null && code == null)
            {
                Uri redirectUri = authContext.GetAuthorizationRequestURL(
                    discoResource,
                    creds.ClientId,
                    new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
                    UserIdentifier.AnyUser,
                    string.Empty);

                return(Redirect(redirectUri.ToString()));
            }

            //Create a DiscoveryClient using the authorization code
            if (disco == null && code != null)
            {
                disco = new DiscoveryClient(new Uri(discoEndpoint), async() =>
                {
                    var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
                        code,
                        new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
                        creds);

                    return(authResult.AccessToken);
                });
            }

            //Discover required capabilities
            CapabilityDiscoveryResult contactsDisco = await disco.DiscoverCapabilityAsync("Contacts");

            CapabilityDiscoveryResult filesDisco = await disco.DiscoverCapabilityAsync("MyFiles");

            Helpers.SaveInCache("ContactsDiscoveryResult", contactsDisco);
            Helpers.SaveInCache("FilesDiscoveryResult", filesDisco);

            List <MyDiscovery> discoveries = new List <MyDiscovery>()
            {
                new MyDiscovery()
                {
                    Capability  = "Contacts",
                    EndpointUri = contactsDisco.ServiceEndpointUri.OriginalString,
                    ResourceId  = contactsDisco.ServiceResourceId,
                    Version     = contactsDisco.ServiceApiVersion
                },
                new MyDiscovery()
                {
                    Capability  = "My Files",
                    EndpointUri = filesDisco.ServiceEndpointUri.OriginalString,
                    ResourceId  = filesDisco.ServiceResourceId,
                    Version     = filesDisco.ServiceApiVersion
                }
            };

            return(View(discoveries));
        }
示例#25
0
        /// <summary>
        /// Use the SharePointClient to get OneDrive for Business Files
        /// </summary>
        /// <param name="code">The authorization code to use when getting an access token</param>
        /// <returns></returns>
        public async Task <ActionResult> Files(string code)
        {
            AuthenticationContext authContext = new AuthenticationContext(
                ConfigurationManager.AppSettings["ida:AuthorizationUri"] + "/common",
                true);

            ClientCredential creds = new ClientCredential(
                ConfigurationManager.AppSettings["ida:ClientID"],
                ConfigurationManager.AppSettings["ida:Password"]);

            //Get the discovery information that was saved earlier
            CapabilityDiscoveryResult cdr = Helpers.GetFromCache("FilesDiscoveryResult") as CapabilityDiscoveryResult;

            //Get a client, if this page was already visited
            SharePointClient sharepointClient = Helpers.GetFromCache("SharePointClient") as SharePointClient;

            //Get an authorization code, if needed
            if (sharepointClient == null && cdr != null && code == null)
            {
                Uri redirectUri = authContext.GetAuthorizationRequestURL(
                    cdr.ServiceResourceId,
                    creds.ClientId,
                    new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
                    UserIdentifier.AnyUser,
                    string.Empty);

                return(Redirect(redirectUri.ToString()));
            }

            //Create the SharePointClient
            if (sharepointClient == null && cdr != null && code != null)
            {
                sharepointClient = new SharePointClient(cdr.ServiceEndpointUri, async() =>
                {
                    var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
                        code,
                        new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
                        creds);

                    return(authResult.AccessToken);
                });

                Helpers.SaveInCache("SharePointClient", sharepointClient);
            }

            //Get the files
            var filesResults = await sharepointClient.Files.ExecuteAsync();

            var fileList = new List <MyFile>();

            foreach (var file in filesResults.CurrentPage.Where(f => f.Name != "Shared with Everyone").OrderBy(e => e.Name))
            {
                fileList.Add(new MyFile
                {
                    Id   = file.Id,
                    Name = file.Name,
                    Url  = file.WebUrl
                });
            }

            //Save the files
            Helpers.SaveInCache("FileList", fileList);

            //Show the files
            return(View(fileList));
        }
示例#26
0
        /// <summary>
        /// Use the OutlookServicesClient to get Exchange contacts
        /// </summary>
        /// <param name="code">The authorization code to use when getting an access token</param>
        /// <returns></returns>
        public async Task <ActionResult> Contacts(string code)
        {
            AuthenticationContext authContext = new AuthenticationContext(
                ConfigurationManager.AppSettings["ida:AuthorizationUri"] + "/common",
                true);

            ClientCredential creds = new ClientCredential(
                ConfigurationManager.AppSettings["ida:ClientID"],
                ConfigurationManager.AppSettings["ida:Password"]);

            //Get the discovery information that was saved earlier
            CapabilityDiscoveryResult cdr = Helpers.GetFromCache("ContactsDiscoveryResult") as CapabilityDiscoveryResult;

            //Get a client, if this page was already visited
            OutlookServicesClient outlookClient = Helpers.GetFromCache("OutlookClient") as OutlookServicesClient;

            //Get an authorization code if needed
            if (outlookClient == null && cdr != null && code == null)
            {
                Uri redirectUri = authContext.GetAuthorizationRequestURL(
                    cdr.ServiceResourceId,
                    creds.ClientId,
                    new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
                    UserIdentifier.AnyUser,
                    string.Empty);

                return(Redirect(redirectUri.ToString()));
            }

            //Create the OutlookServicesClient
            if (outlookClient == null && cdr != null && code != null)
            {
                outlookClient = new OutlookServicesClient(cdr.ServiceEndpointUri, async() =>
                {
                    var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
                        code,
                        new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
                        creds);

                    return(authResult.AccessToken);
                });

                Helpers.SaveInCache("OutlookClient", outlookClient);
            }

            //Get the contacts
            var contactsResults = await outlookClient.Me.Contacts.ExecuteAsync();

            List <MyContact> contactList = new List <MyContact>();

            foreach (var contact in contactsResults.CurrentPage.OrderBy(c => c.Surname))
            {
                contactList.Add(new MyContact
                {
                    Id             = contact.Id,
                    GivenName      = contact.GivenName,
                    Surname        = contact.Surname,
                    DisplayName    = contact.Surname + ", " + contact.GivenName,
                    CompanyName    = contact.CompanyName,
                    EmailAddress1  = contact.EmailAddresses.FirstOrDefault().Address,
                    BusinessPhone1 = contact.BusinessPhones.FirstOrDefault(),
                    HomePhone1     = contact.HomePhones.FirstOrDefault()
                });
            }

            //Save the contacts
            Helpers.SaveInCache("ContactList", contactList);

            //Show the contacts
            return(View(contactList));
        }
示例#27
0
        /// <summary>
        /// Checks that an OutlookServicesClient object is available.
        /// </summary>
        /// <returns>The OutlookServicesClient object. </returns>
        public static async Task <OutlookServicesClient> GetOutlookClientAsync(string capability)
        {
            if (_outlookClient != null)
            {
                return(_outlookClient);
            }
            else
            {
                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.
#if WINDOWS_APP
                    _authenticationContext = new AuthenticationContext(authority);
#endif
#if WINDOWS_PHONE_APP
                    _authenticationContext = await AuthenticationContext.CreateAsync(authority);
#endif

#if WINDOWS_APP
                    // 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;
#endif

                    //See the Discovery Service Sample (https://github.com/OfficeDev/Office365-Discovery-Service-Sample)
                    //for an approach that improves performance by storing the discovery service information in a cache.
                    DiscoveryClient discoveryClient = new DiscoveryClient(
                        async() => await GetTokenHelperAsync(_authenticationContext, DiscoveryResourceId));

                    // Get the specified capability ("Mail").
                    CapabilityDiscoveryResult result =
                        await discoveryClient.DiscoverCapabilityAsync(capability);

                    var token = await GetTokenHelperAsync(_authenticationContext, result.ServiceResourceId);

                    // Check the token
                    if (String.IsNullOrEmpty(token))
                    {
                        // User cancelled sign-in
                        return(null);
                    }
                    else
                    {
                        _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)
                {
                    // Discovery failed.
                    Debug.WriteLine("Exception: " + dfe.Message);
                    _authenticationContext.TokenCache.Clear();
                    return(null);
                }
                catch (ArgumentException ae)
                {
                    // Argument exception
                    Debug.WriteLine("Exception: " + ae.Message);
                    _authenticationContext.TokenCache.Clear();
                    return(null);
                }
            }
        }
        private static async Task ExecuteSearchQuery(List<SearchResult> results, CapabilityDiscoveryResult dcr, string sharePointToken, string query)
        {
            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + sharePointToken);
            client.DefaultRequestHeaders.Add("Accept", "application/json; odata=verbose");
            using (HttpResponseMessage response = await client.GetAsync(new Uri(dcr.ServiceEndpointUri + query, UriKind.Absolute)))
            {
                if (response.IsSuccessStatusCode)
                {
                    XElement root = SearchModel.Json2Xml(await response.Content.ReadAsStringAsync());
                    var items = root.Descendants("RelevantResults").Elements("Table").Elements("Rows").Elements("results").Elements("item");
                    foreach (var item in items)
                    {
                        //loop through the properties returned for this item
                        var newItem = new SearchResult();
                        foreach (var prop in item.Descendants("item"))
                        {
                            if (prop.Element("Key").Value == "Title")
                                newItem.Title = prop.Element("Value").Value;
                            else if (prop.Element("Key").Value == "Path")
                                newItem.Path = prop.Element("Value").Value;
                            else if (prop.Element("Key").Value == "SiteLogo")
                                newItem.SiteLogo = prop.Element("Value").Value;
                            else if (prop.Element("Key").Value == "contentclass")
                                newItem.ContentClass = prop.Element("Value").Value;
                        }

                        //only return site collections in primary domain...not the onedrive or public domains
                        //this would probably be better placed in the original search query
                        if (newItem.Path.ToLower().Contains(dcr.ServiceResourceId.ToLower()))
                            results.Add(newItem);
                    }
                }
            }
        }
        public static async Task<string> GetAccessTokenForResourceAsync(CapabilityDiscoveryResult discoveryCapabilityResult)
        {
            var authResult = await authContext.AcquireTokenSilentAsync(discoveryCapabilityResult.ServiceResourceId, ClientId);

            return authResult.AccessToken;
        }
示例#30
0
        public static async Task <string> GetAccessTokenForResourceAsync(CapabilityDiscoveryResult discoveryCapabilityResult)
        {
            var authResult = await authContext.AcquireTokenSilentAsync(discoveryCapabilityResult.ServiceResourceId, ClientId);

            return(authResult.AccessToken);
        }