如何在 C# 中使用带有客户端 ID 和客户端密码的 SharePoint rest API 来获取网站集?

问题描述

有什么方法可以将 SharePoint Rest API 与 C# 中的客户端凭据连接起来以获取站点分类?我以前使用 Graph API 来获取这些集合,但我需要使用 SharePoint Rest API。

 IConfidentialClientApplication CCA = ConfidentialClientApplicationBuilder
              .Create(c_Id).WithTenantId(t_Id).WithClientSecret(clientSecret).Build();
 ClientCredentialProvider CCP = new ClientCredentialProvider(CCA);
 GraphServiceClient g_Client = new GraphServiceClient(CCP);
 var Sites = await g_Client.Sites.Request().GetAsync();

我使用上面的代码来处理 Graph API,如何使用 SharePoint rest API 做同样的事情?

解决方法

SharePoint Online 已阻止除证书之外的 Azure AD 应用程序客户端密钥:

enter image description here

因此需要为 Azure AD 应用创建自签名证书并上传:

enter image description here

创建证书请参考官方文档,使用PowerShell创建:

Granting access via Azure AD App-Only

首先在 C# 代码中,例如创建一个名为 TokenProvider 的类并填充以下代码片段:

using Microsoft.Identity.Client;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;

     class TokenProvider
        {
            public static async Task<string> GetAccessTokenAsync(string endpoint)
            {
                var clientId = "yourclientId";
                var tenantId = "yourtenantId";
                
                var certificate = GetCertificate(Path.Combine("D:\\","certificatename.pfx"),"certificatepwd");
                var confidentialClient = ConfidentialClientApplicationBuilder.Create(clientId).WithTenantId(tenantId).WithCertificate(certificate).Build();
               
                var token = await confidentialClient.AcquireTokenForClient(new[] { $"{endpoint.TrimEnd('/')}/.default" }).ExecuteAsync();
    
                return token.AccessToken;
            }
    
            private static X509Certificate2 GetCertificate(string path,string password)
            {
                return new X509Certificate2(path,password,X509KeyStorageFlags.MachineKeySet);
            }
        }

然后在 Main() 函数中这样调用:

       var siteUrl = "https://tenantname.sharepoint.com/";

        var token = await TokenProvider.GetAccessTokenAsync(new Uri(siteUrl).GetLeftPart(UriPartial.Authority));

        var url = "https://tenantName.sharepoint.com/_api/search/query?querytext='contentclass:sts_site'";
        
        var client = new WebClient();
        client.Headers[HttpRequestHeader.Accept] ="application/json;odata=verbose";
        client.Headers[HttpRequestHeader.ContentType] ="application/json;odata=verbose";
        client.Headers[HttpRequestHeader.Authorization] = "Bearer " + token;
        var json = client.DownloadString(url);

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...