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

How to use SharePoint rest API with Client ID and Client Secret in C# to get site collection?

是否有任何方法可以将 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 应用客户端密码:

因此有必要为 Azure AD 应用程序创建一个自签名证书并上传:

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

Granting access via Azure AD App-Only

首先在 C# 代码中,创建一个名为 class 的 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);