2

My goal is to call REST API and retrieve specific folder and files metadata to specific site. I wrote a console application in C#. The SharePoint site is multi-factor enabled and I can get the site lists in success:

var authenticationManager = new OfficeDevPnP.Core.AuthenticationManager();
ClientContext context = authenticationManager.GetWebLoginClientContext(@"https://XXX-admin.sharepoint.com/", null);
GetAllSiteCollections(context);

However I have no idea why I get credential error when calling function GetFilesPropertiesFromSite:

Message: The request was aborted: The request was canceled.
InnerException: Microsoft.SharePoint.Client.IdcrlException: Identity Client Runtime Library (IDCRL) could not look up the realm information for a federated sign-in.
at Microsoft.SharePoint.Client.Idcrl.IdcrlAuth.GetUserRealm(String login)
at Microsoft.SharePoint.Client.Idcrl.IdcrlAuth.GetServiceToken(String username, String password, String serviceTarget, String servicePolicy)
at Microsoft.SharePoint.Client.Idcrl.SharePointOnlineAuthenticationProvider.GetAuthenticationCookie(Uri url, String username, SecureString password, Boolean alwaysThrowOnFailure, EventHandler`1 executingWebRequest)
at Microsoft.SharePoint.Client.SharePointOnlineCredentials.GetAuthenticationCookie(Uri url, Boolean refresh, Boolean alwaysThrowOnFailure)
at Microsoft.SharePoint.Client.SharePointOnlineAuthenticationModule.GetSpoAuthCookieAndUpdateRequest(WebRequest request, SharePointOnlineCredentials spoCredentials, Boolean preAuthentication)
at Microsoft.SharePoint.Client.SharePointOnlineAuthenticationModule.Authenticate(String challenge, WebRequest request, ICredentials credentials)
at System.Net.AuthenticationManagerDefault.Authenticate(String challenge, WebRequest request, ICredentials credentials)
at System.Net.AuthenticationState.AttemptAuthenticate(HttpWebRequest httpWebRequest, ICredentials authInfo)
at System.Net.HttpWebRequest.CheckResubmitForAuth()
at System.Net.HttpWebRequest.CheckResubmit(Exception& e, Boolean& disableUpload)
at System.Net.HttpWebRequest.DoSubmitRequestProcessing(Exception& exception)
at System.Net.HttpWebRequest.ProcessResponse()
at System.Net.HttpWebRequest.SetResponse(CoreResponseData coreResponseData)

Code:

private static void GetFilesPropertiesFromSite()
        {
            try
            {
                Console.WriteLine("Enter admin username: ");
                string username = Console.ReadLine();
                Console.WriteLine("Enter password: ");
                string password = Console.ReadLine();

                var Uri = new Uri(@"https://XXX.sharepoint.com/sites/AL/");
                var credentials = PrepareSPOCredentials(username, password);
                var result = ExecuteSearchRequest(Uri, credentials, "contentclass:STS_ListItem AND ContentType:Task");

            }
            catch (Exception ex)
            {
                Console.WriteLine("Message: " + ex.Message);
                Console.WriteLine("InnerException: " + ex.InnerException);
            }
        }

        private static SharePointOnlineCredentials PrepareSPOCredentials(string userName, string passWord)
        {
            var securePassWord = new SecureString();
            foreach (var c in passWord.ToCharArray()) securePassWord.AppendChar(c);
            var credentials = new SharePointOnlineCredentials(userName, securePassWord);
            return credentials;
        }

Do anyone has the same issue before? Please give me some comment/sample code. Appreciate for your help!

1

You could call rest with Credential in SPO like this:

 private async Task test()
        {
            Task<string> getStringTask = getWebTitle("https://xxx.sharepoint.com/sites/xxx/");
            string data = await getStringTask;

        }
        private static async Task<string> getWebTitle(string webUrl)
        {
            //Creating Password 
            const string PWD = "xxx";
            const string USER = "xxx@xxx.onmicrosoft.com";
            const string RESTURL = "{0}/_api/web?$select=Title";

            //Creating Credentials 
            var passWord = new SecureString();
            foreach (var c in PWD) passWord.AppendChar(c);
            var credential = new SharePointOnlineCredentials(USER, passWord);

            //Creating Handler to allows the client to use credentials and cookie 
            using (var handler = new HttpClientHandler() { Credentials = credential })
            {
                //Getting authentication cookies 
                Uri uri = new Uri(webUrl);
                handler.CookieContainer.SetCookies(uri, credential.GetAuthenticationCookie(uri));

                //Invoking REST API 
                using (var client = new HttpClient(handler))
                {
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    HttpResponseMessage response = await client.GetAsync(string.Format(RESTURL, webUrl)).ConfigureAwait(false);
                    response.EnsureSuccessStatusCode();

                    string jsonData = await response.Content.ReadAsStringAsync();

                    return jsonData;
                }
            }
        }

enter image description here

0

Try using username format first.last@mytenant.onmicrosoft.com instead of first.last@mytenant.com.

  • Thanks, but it throws the error: The sign-in name or password does not match one in the Microsoft account system. The account is just the site administrator. Is it necessary to use global admin to call API? – Angela Aug 29 '18 at 1:17

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.