微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何在 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);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。