1

I am trying to access the SharePoint sites using O365 Api in MVC asp.net application as mentioned in the github sample O365SharePointFilePush, But facing the error with message Error : Failed to acquire token silently. Call method AcquireToken at the code line

  var dcr = await discClient.DiscoverCapabilityAsync("RootSite");

in the HomeController.cs

please find my controller code

[Authorize]
        public async Task<ActionResult> Sites()
        {


            //string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
            //AuthenticationContext authContext = new AuthenticationContext(Startup.Authority, new NaiveSessionCache(userObjectID));
            //ClientCredential credential = new ClientCredential(clientId, appKey);
            //result = await authContext.AcquireTokenSilentAsync(todoListResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

            List<SearchResult> results = new List<SearchResult>();

            var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
            var 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));

            try
            {
                DiscoveryClient discClient = new DiscoveryClient(SettingsHelper.DiscoveryServiceEndpointUri,
                    async () =>
                    {
                        // var authResultDisc = await authContext.AcquireTokenSilent(SettingsHelper.DiscoveryServiceResourceId, SettingsHelper.ClientId, new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));
                        var authResultDisc = await authContext.AcquireTokenSilentAsync(SettingsHelper.DiscoveryServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));
                        // var authResultDisc = await authContext.AcquireTokenAsync(SettingsHelper.DiscoveryServiceResourceId,SettingsHelper.ClientId, new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));
                        return authResultDisc.AccessToken;
                    });

                var dcr = await discClient.DiscoverCapabilityAsync("RootSite");

                ViewBag.ResourceId = dcr.ServiceResourceId;

                var authResultSharePoint = await authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId,
                    new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                var sharePointToken = authResultSharePoint.AccessToken;

                results.Add(new SearchResult
                {
                    Title = "Root Site",
                    Path = dcr.ServiceResourceId,
                });

                var query = "/search/query?querytext='contentclass:sts_site'&trimduplicates=true&rowlimit=50&SelectProperties='WebTemplate,Title,Path,SiteLogo,contentclass'";

                await ExecuteSearchQuery(results, dcr, sharePointToken, query);

            }
            catch (AdalException exception)
            {
                //handle token acquisition failure
                if (exception.ErrorCode == AdalError.FailedToAcquireTokenSilently)
                {
                    authContext.TokenCache.Clear();

                    ViewBag.ErrorMessage = "AuthorizationRequired";
                }
            }

            return View(results);
        }

I tries another sample O365-ASPNETMVC-Start which gives the same issue. I hope that this is the issue with authentication model since both github examples are very old.Can any one help me on this or provide latest examples for accessing SharePoint in MVC using Office 365 APIs into .NET Visual Studio projects .

Note: App has given all necessary rights by the admin in Azure AD.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.