问题
I want to get the list of all the users who have a particular role/permission on a site. For example, I need the list of users who have edit rights (RoleType=Editor) using .Net CSOM in SharePoint 2013. They can be in any group. I tried many things. However, it seems there isn't a straight forward way to do this. Any ideas?
Thanks in adavance.
回答1:
You could utilize Web.GetUserEffectivePermissions method to gets the effective permissions that the specified user has within the web site.
Example 1: Getting users by permission
The first example demonstrates how to retrieve users by permission, in particular users who can edit list items (using 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);
}
}
}
Example 2: getting users by role
In case of role type or permission levels the example become a little more complicated since we need to:
- retrieve the list of permissions for a role type (step 1 and 2)
- get users with permissions (step 3 and 4)
- filter users by role permissions (step 5)
Example:
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);
}
}
}
来源:https://stackoverflow.com/questions/27862632/get-all-the-users-based-on-a-specific-permission-using-csom-in-sharepoint-2013