我正在构建一个快速工具,使用多重身份验证 (MFA) 对 Microsoft Sharepoint 中的某些文件进行自动处理。我可以使用 PnP Powershell 命令打开连接:
Connect-PnPOnline -interactive -url "https://[tenantName].sharepoint.com"
重要的是,使用上述方法,我不需要 client-id、client-secret、tennant-id 等来登录,因为我没有 Sharepoint 租户的管理员访问权限,相反,我的登录只需访问我想在 .net 控制台应用程序中读取和处理的文件子集(而不是上面的 PowerShell)。
是否有一种快速、简单的方法来模拟使用
Connect-PnPOnline
命令看到的上述交互行为,但是来自 asp.net 控制台应用程序(用 C# 编写) - 用户可以通过该方法自行登录,然后登录 .net 应用程序可以访问 Sharepoint 上的文件吗?
要使用 Azure AD 身份验证访问 SharePoint 资源,您通常需要在 Azure AD 中注册应用程序并获取客户端 ID(也称为应用程序 ID)。
此客户端 ID 对于识别和验证您的应用程序访问 SharePoint 至关重要。
using Microsoft.Identity.Client;
using Microsoft.Graph;
using System;
using System.Threading.Tasks;
class Program
{
private const string graphScope = "https://graph.microsoft.com/.default";
private const string sharePointScope = "https://[tenantName].sharepoint.com/.default";
static async Task Main(string[] args)
{
var app = PublicClientApplicationBuilder.Create(null)
.WithAuthority(AzureCloudInstance.AzurePublic, "[tenantId]")
.Build();
var scopes = new[] { graphScope, sharePointScope };
try
{
var result = await app.AcquireTokenInteractive(scopes)
.WithPrompt(Prompt.SelectAccount)
.WithUseEmbeddedWebView(true)
.ExecuteAsync();
var graphClient = new GraphServiceClient(
new DelegateAuthenticationProvider(
async (requestMessage) =>
{
requestMessage.Headers.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", result.AccessToken);
}));
// Use graphClient to access SharePoint or Graph API resources
// For example:
var driveItems = await graphClient
.Sites["{site-id}"]
.Drive
.Root
.Children
.Request()
.GetAsync();
foreach (var item in driveItems)
{
Console.WriteLine(item.Name);
}
}
catch (MsalException ex)
{
Console.WriteLine($"Error acquiring token: {ex.Message}");
}
}
}