如何指定Sharepoint凭据?

时间:2019-04-29 21:18:23

标签: sharepoint

我有一个使用Sharepoint的.NET应用程序。在应用程序代码中,我使用ICredentials指定要分配给ClientContext对象的Credentials属性的用户名和密码。

这很好,但是,我希望能够从邮递员之类的REST工具中访问Sharepoint,以便更轻松地测试和调试请求。在这种情况下,我不知道如何指定凭据。我尝试发送基本的auth标头,但是没有用。

坦率

1 个答案:

答案 0 :(得分:0)

示例代码供您参考。

private static async Task<string> getWebTitle(string webUrl)
        {
            //Creating Password 
            const string PWD = "password";
            const string USER = "user@tenant.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;
                }
            }
        }
        static void Main(string[] args)
        {

            //Creating Password 
            string webUrl = "https://tenant.sharepoint.com/sites/lee";
            var data=getWebTitle(webUrl).GetAwaiter().GetResult();
            Console.WriteLine("done");
            Console.ReadKey();
        }