问题描述
当我们将项目从 .net 4.7 迁移到 .Net core 3.1 时,我不得不寻找 SharePointOnlineCredentials 类的替代方法。
为了生成我的 ClientContext,我现在使用 Pnp.Framework 包中的 AuthenticationManager。
但是,我无法再更新 Sharepoint 用户属性。 我收到错误:
'访问被拒绝。您无权执行此操作或访问此资源。'
每当我使用 SharePoint 管理员用户(像以前一样)或具有 Uer.ReadWrite.All 权限的注册 AAD 应用时。
using(var am = PnP.Framework.AuthenticationManager.CreateWithCredentials(clientId,userName,password))
using (var clientContext = am.GetContext(adminSiteUrl))
{
var peopleManager = new PeopleManager(clientContext);
var personProperties = peopleManager.GetPropertiesFor(accountName);
clientContext.Load(personProperties);
clientContext.ExecuteQuery();
peopleManager.SetSingleValueProfileProperty(personProperties.AccountName,"officeKey","MTR");
clientContext.ExecuteQuery(); //Throws the 'Access Denied' exception here
}
我使用已注册的客户端应用进行测试(使用证书)
using (var am = new PnP.Framework.AuthenticationManager(clientId,certificatePath,certificatePassword,tenant))
using (var clientContext = am.GetContext(adminSiteUrl))
{
var peopleManager = new PeopleManager(clientContext);
var personProperties = peopleManager.GetPropertiesFor(accountName);
clientContext.Load(personProperties);
clientContext.ExecuteQuery();
peopleManager.SetSingleValueProfileProperty(personProperties.AccountName,"MTR");
clientContext.ExecuteQuery(); //Throws the 'Access Denied' exception here
}
注意:我在 AAD 中注册的应用客户端拥有所有 SharePoint API 权限。
我的项目正在引用包:
- Microsoft.SharePointOnline.CSOM (16.1.20912.12000)
- Pnp.Framework (1.2.0)
解决方法
我终于通过在 SharePoint(而不是 AAD)中注册一个应用程序使其正常工作。
您首先需要通过创建 clientId 和 clientSecret 来注册应用程序:https://<tenant>-admin.sharepoint.com/_layouts/15/appregnew.aspx
然后你需要授予权限:https://<tenant>-admin.sharepoint.com/_layouts/15/appinv.aspx
您需要授予以下权限:
<AppPermissionRequests AllowAppOnlyPolicy="true">
<AppPermissionRequest Scope="http://sharepoint/content/tenant" Right="FullControl" />
<AppPermissionRequest Scope="http://sharepoint/social/tenant" Right="FullControl" />
</AppPermissionRequests>
然后您将能够获取用户属性:
using (var clientContext = new PnP.Framework.AuthenticationManager().GetACSAppOnlyContext(siteUrl,appId,appSecret))
{
var peopleManager = new PeopleManager(clientContext);
var personProperties = peopleManager.GetPropertiesFor(accountName);
clientContext.Load(personProperties);
clientContext.ExecuteQuery();
peopleManager.SetSingleValueProfileProperty(personProperties.AccountName,"officeKey","MTR");
clientContext.ExecuteQuery(); //Throws the 'Access Denied' exception here
}