我想获取在网站上拥有特定角色/权限的所有用户的列表。例如,我需要在SharePoint 2013中使用 .Net CSOM 具有编辑权限(RoleType =编辑器)的用户列表。它们可以位于任何组中。我尝试了很多东西。但是,似乎没有直接的方法来做到这一点。有任何想法吗?
谢谢你。
答案 0 :(得分:4)
您可以利用Web.GetUserEffectivePermissions method获取指定用户在网站中拥有的有效权限。
示例1:获取用户许可
第一个示例演示了如何通过权限检索用户,特别是可以编辑列表项的用户(使用PermissionKind.EditListItems):
using (var ctx = new ClientContext(webUri))
{
//Retrieve site users
var users = ctx.LoadQuery(ctx.Web.SiteUsers.Where(u => u.PrincipalType == PrincipalType.User));
ctx.ExecuteQuery();
//Retrieve users permissions
var userPermissionsResults = users.ToDictionary(user => user, user => ctx.Web.GetUserEffectivePermissions(user.LoginName));
ctx.ExecuteQuery();
//Filter the users who can edit list items
var usersCanEditListItems = new List<User>();
foreach (var result in userPermissionsResults)
{
var user = result.Key;
var userPermissions = result.Value.Value;
if (userPermissions.Has(PermissionKind.EditListItems))
{
usersCanEditListItems.Add(user);
}
}
}
示例2:按角色获取用户
如果角色类型或权限级别,示例会变得有点复杂,因为我们需要:
示例:
using (var ctx = new ClientContext(webUri))
{
//1.Retrieve role definition
var roleDef = ctx.Web.RoleDefinitions.GetByType(RoleType.Editor);
ctx.Load(roleDef);
ctx.ExecuteQuery();
//2.Get permission levels for role
var permLevelNames = Enum.GetNames(typeof (PermissionKind));
var permissionLevels = permLevelNames.Select(permLevelName => (PermissionKind) Enum.Parse(typeof (PermissionKind), permLevelName)).Where(permissionLevel => roleDef.BasePermissions.Has(permissionLevel)).ToList();
//3.Retrieve users
var users = ctx.LoadQuery(ctx.Web.SiteUsers.Where(u => u.PrincipalType == PrincipalType.User ));
ctx.ExecuteQuery();
//4.Retrieve users permissions
var userPermissionsResults = users.ToDictionary(user => user, user => ctx.Web.GetUserEffectivePermissions(user.LoginName));
ctx.ExecuteQuery();
//5.Filter users by role
var editorUsers = new List<User>();
foreach (var result in userPermissionsResults)
{
var user = result.Key;
var userPermissions = result.Value.Value;
var hasPermissions = permissionLevels.All(userPermissions.Has); //has the same permissions?
if (hasPermissions)
{
editorUsers.Add(user);
}
}
}