首页 > 解决方案 > 如何使用客户端 ID 和客户端密码在 C# .NET Framework 中使用 SharePoint Rest API?

问题描述

有什么方法可以使用客户端 ID 和客户端密钥对带有 SharePoint REST API(如 Graph API)的应用程序进行身份验证?我想在我的控制台应用程序中使用 SharePoint REST API。

标签: c#sharepointmicrosoft-graph-apisharepoint-onlinesharepoint-rest-api

解决方案


这对我有用:

在 Azure Active Directory 中,我为 SharePoint API 配置了权限。 在此处输入图像描述

在我的代码中,我以这种方式定义了范围:

var scopes = new [] {"https://<tenantName>.sharepoint.com/allsites.manage"};

var clientApp = ConfidentialClientApplicationBuilder.Create($"{clientId}")
            .WithAuthority($"https://login.microsoftonline.com/{tenantId}")
            .WithClientSecret($"{clientSecret}").Build();

// acquire a token for the app
AuthenticationResult result = null;
try
{
    result = await clientApp.AcquireTokenForClient(scopes)
                             .ExecuteAsync();
}
catch (MsalUiRequiredException ex)
{
...
}
catch (MsalServiceException ex)
{
...
}

推荐阅读