gpt4 book ai didi

c# - CSOM 在线共享点出现问题

转载 作者:行者123 更新时间:2023-12-03 02:29:36 27 4
gpt4 key购买 nike

我在使用 CSOM 时遇到了一些问题。

我正在尝试获取 Sharepoint 网站的标题,但不幸的是我收到此错误 => 远程服务器返回错误:(401) 未经授权

using (var context = GetClientContext("https://tenant.sharepoint.com/"))
{
context.Load(context.Web, p => p.Title);
await context.ExecuteQueryAsync();
Console.WriteLine($"Title: {context.Web.Title}");
}

public ClientContext GetClientContext(string targetUrl)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.ExecutingWebRequest +=
delegate (object oSender, WebRequestEventArgs webRequestEventArgs)
{
string token = GetToken();
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + token;
};
return clientContext }



public string GetToken()
{
IConfidentialClientApplication app;
var instance = "https://login.microsoftonline.com/{0}";
var tenant = "tenantId";
var authority = String.Format(CultureInfo.InvariantCulture, instance, tenant);
string[] scopes = new string[] { "https://tenant.sharepoint.com/.default" };

app = ConfidentialClientApplicationBuilder
.Create("clientId")
.WithClientSecret("secretId")
.WithAuthority(new Uri(authority))
.Build();

AuthenticationResult result = app.AcquireTokenForClient(scopes)
.ExecuteAsync().GetAwaiter().GetResult();
return result.AccessToken;
}

这是应用程序注册的权限 App Registration

但我可以从图形调用中获取它

最佳答案

如果要在 SharePoint Online CSOM 中使用“仅应用程序”权限,请使用以下 URL 注册 SharePoint 外接程序而不是 Azure AD:

https://tenant.sharepoint.com/_layouts/15/appregnew.aspx

enter image description here

然后使用 https://TenantName-admin.sharepoint.com/_layouts/15/appinv.aspx 中的此 xml 设置加载项权限:

<AppPermissionRequests AllowAppOnlyPolicy="true">    
<AppPermissionRequest Scope="http://sharepoint/content/tenant" Right="FullControl" />
</AppPermissionRequests>

enter image description here

然后安装SharePointPnPCoreOnline使用Nuget打包并调用如下:

using OfficeDevPnP.Core;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Client;

string siteUrl = "https://tenant.sharepoint.com/sites/demo";
using (var cc = new AuthenticationManager().GetAppOnlyAuthenticatedContext(siteUrl, "[Your Client ID]", "[Your Client Secret]"))
{
cc.Load(cc.Web, p => p.Title);
cc.ExecuteQuery();
Console.WriteLine(cc.Web.Title);
};

这里是一个完整的演示供您引用:

Connect To SharePoint Online Site With App Only Authentication

关于c# - CSOM 在线共享点出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65706437/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com