SharePoint 仅应用身份验证抛出“远程服务器返回错误:(401) 未经授权。”

时间:2021-01-12 13:49:55

标签: c# oauth sharepoint-online

我正在尝试使用 oAuth 或 App-Only 身份验证进行共享点身份验证,但出现错误“远程服务器返回错误:(401) 未经授权。”

我正在使用试用 sharepoint 租户。

这是我的代码片段:

使用客户端 ID 和客户端密码:

string siteUrl = "[Sharepoint-Site-URL]";

//Sharepoint App details
string SPClientId = @"[Client-id]";
string SPClientSecret = @"[Client-secret]";
using (ClientContext context = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(siteUrl, SPClientId, SPClientSecret))
 {
     context.Load(context.Web, t => t.Title);
     context.ExecuteQuery();
     Console.WriteLine(context.Web.Title);
 };

使用访问令牌:

 string siteUrl = "[Sharepoint-Site-URL]";
 string realm = TokenHelper.GetRealmFromTargetUrl(new Uri(siteUrl));

 //Get the access token for the URL.  
 string accessToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, new Uri(siteUrl).Authority, realm).AccessToken;

 //Create a client context object based on the retrieved access token
 using (ClientContext context = TokenHelper.GetClientContextWithAccessToken(siteUrl, accessToken))
 {
    context.Load(cc.Web, t => t.Title);
    context.ExecuteQuery();
    Console.WriteLine(cc.Web.Title);
 }
enter code here

我参考了以下文章: https://docs.microsoft.com/en-us/sharepoint/dev/solution-guidance/security-apponly-azureacs https://www.c-sharpcorner.com/article/connect-to-sharepoint-online-site-with-app-only-authentication/

1 个答案:

答案 0 :(得分:1)

这可能是您的租户中禁用了仅限 SharePoint 应用的权限。

您可以运行命令来启用它:Set-SPOTenant -DisableCustomAppAuthentication $false