【发布时间】:2021-01-13 16:59:48
【问题描述】:
我在使用 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;
}
这是 appRegistration 的权限 App Registration
但我可以从图形调用中得到它
【问题讨论】:
-
你有一个有效的令牌吗?
-
对我来说这似乎是有效的。怎么查?
-
服务器是否与浏览器一起工作?可以在浏览器中进行查询并在查询中包含令牌吗?通常您可以从 URL myURL?parameter1=123¶meter2=345&token=678 查询大多数网站。
标签: c# azure .net-core sharepoint csom