如何授权 .NET 5.0/C# 应用程序在没有用户交互的情况下与 Microsoft 365 SharePoint Online 交互?

How can I authorize a .NET 5.0 / C# application to interact with Microsoft 365 SharePoint Online without user interaction?

我需要创建一个 Web 服务,它将接受来自用户的文件,解析文件中的数据,assemble 存储在 Sharepoint 上的文件集合,以及 return 包含的 zip 文件这些文件给用户。 用户可能无法直接访问 Sharepoint,将来甚至可能没有人类用户参与,因为文件可能会在计时器上自动从另一个系统中提取。

我正在用 C# 创建解决方案,并且正在努力创建一个可以成功对 Sharepoint 进行身份验证的客户端。

目前,我正在尝试使用 Microsoft 文档中的 CSOM Authentication Manager,但使用 Visual Studio 调试器时,我发现此方法失败:

        private async Task<string> AcquireTokenAsync(Uri resourceUri, string username, string password)
        {
            string resource = $"{resourceUri.Scheme}://{resourceUri.DnsSafeHost}";

            var clientId = defaultAADAppId;
            var body = $"resource={resource}&client_id={clientId}&grant_type=password&username={HttpUtility.UrlEncode(username)}&password={HttpUtility.UrlEncode(password)}";
            using (var stringContent = new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded"))
            {

                var result = await httpClient.PostAsync(tokenEndpoint, stringContent).ContinueWith((response) =>
                {
                    return response.Result.Content.ReadAsStringAsync().Result;
                }).ConfigureAwait(false);

                var tokenResult = JsonSerializer.Deserialize<JsonElement>(result);
                var token = tokenResult.GetProperty("access_token").GetString();
                return token;
            }
        }

结果值为:

"{"error":"unauthorized_client","error_description":"AADSTS700016: Application with identifier '986002f6-c3f6-43ab-913e-78cca185c392' was not found in the directory 'enpal.de'. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You may have sent your authentication request to the wrong tenant.\r\nTrace ID: d3b47a0b-54bc-40fd-a731-b99732326200\r\nCorrelation ID: 158621cc-3052-4c7b-9532-e2bab5c3cc09\r\nTimestamp: 2020-11-18 13:46:39Z","error_codes":[700016],"timestamp":"2020-11-18 13:46:39Z","trace_id":"d3b47a0b-54bc-40fd-a731-b99732326200","correlation_id":"158621cc-3052-4c7b-9532-e2bab5c3cc09","error_uri":"https://login.microsoftonline.com/error?code=700016"}"

resourceUri、用户名和密码值与我将直接用于登录网站的值正确对应。我的管理员已向我保证该用户是网站的管理员,因此应该拥有执行任何操作所需的所有可能权限,包括连接。

有谁知道如何进行这项工作?
或者知道更可能有效的不同解决方案? 或者知道必须在 SharePoint 端配置什么才能使此解决方案起作用吗?

您似乎从 Microsoft 网站获取了代码示例并跳过了重要部分:Configuring an application in Azure AD ;)

目前,您正在尝试连接到您的租户作为 ID 为“986002f6-c3f6-43ab-913e-78cca185c392”的应用程序,这是代码示例中的占位符。在您的租户中注册您的应用程序,并在您的 defaultAADAppId 常量中插入正确的应用程序 ID。