how check if CurrentUser is member of group AD? - sharepoint

This code is not suitable:
web.IsCurrentUserMemberOfGroup(web.Groups["Namegruop"].ID);

You need to distinguish between AD security group membership and SharePoint group membership.
In order to check AD security membership you can use System.Security.Principal.WindowsPrincipal.IsInRole. You do not need to use the SharePoint API:
using(WindowsIdentity identity = WindowsIdentity.GetCurrent())
{
WindowsPrincipal p = new WindowsPrincipal(identity);
if (p.IsInRole("DOMAIN\\GroupName")) // Alternative overloads with SecurityIdentifier available
{
// ...
}
}
To check if the current user is member of a SharePoint group you can use the SharePoint API:
SPWeb web = // ...
SPGroup group = web.SiteGroups["GroupName"];
if (group.ContainsCurrentUser)
{
// ...
}

Related

Accessing Azure Assigned Groups via Razor or Controllers in ASP.NET Core

My ASP.NET Core web app is using an Azure Active Directory tenant and using OpenID Connect to sign-in users. I'm able to login successfully and I'm able to view the full list of Claims on a user with the following code:
return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
My security token includes the following "groups":
{
type: "groups",
value: "e8f1a447-336a-47bb-8c26-79f1183f989f"
},
{
type: "groups",
value: "38421450-61ba-457b-bec2-e908d42d6b92"
}
I'm having trouble trying to determine how to capture these groups to perform logic in my Razor views and controllers. For example, I need to hide/show a button in my Razor view depending on whether a user is in a specific group. In my controllers I may need to allow/deny an action.
What is the standard/preferred method to do this in ASP.NET Core?
When Azure AD adds applicable group claims to the token it issues for users, the value for the group claim will be the Object ID of the security group and not the name of the security group(a group’s name can be changed in the directory so it is not a reliable identifier for the group ) .You could check whether the user’s existence in the security group in controller by :
// Look for the groups claim for the 'Dev/Test' group.
const string devTestGroup = "99dbdfac-91f7-4a0f-8eb0-57bf422abf29";
Claim groupDevTestClaim = User.Claims.FirstOrDefault(
c => c.Type == "groups" &&
c.Value.Equals(devTestGroup, StringComparison.CurrentCultureIgnoreCase));
// If the app has write permissions and the user is in the Dev/Test group...
if (null != groupDevTestClaim)
{
//
// Code to add the resource goes here.
//
ViewBag.inGroup = true;
}
else
{
ViewBag.inGroup = false;
}
Then in view , you could control whether show/hide links/buttons :
#if (ViewBag.inGroup)
{
<div>show/hide button/link goes here</div>
}
In your AppSettings.json, add your group's name and GUID object ID:
"AzureAdAuthorizationGroups": {
"MyGroup": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
}
Next, hook up authorisation in your Startup.cs ConfigureServices method
services.AddAuthorization(options => {
options.AddPolicy("MyGroup", policyBuilder => policyBuilder.RequireClaim("groups", Configuration.GetValue<string>("AzureAdAuthorizationGroups:MyGroup")));
});
Finally in your view:
#if ((await AuthorizationService.AuthorizeAsync(User, "MyGroup")).Succeeded)
{
// ...
}

How to get all users of a site role in Liferay 6.1?

I have LDAP imported user groups which I have mapped to site roles (as mapping them to organization roles was not possible for Liferay 6.1).
So for example I have mapped the user group 'my_site administrators' to the site role 'Site Administrators' of the site 'my_site'.
How can I get all the users that are members of a site role taking into account the user group memberships too?
I have tried the following code but did not work.
Set<User> siteMembers = new HashSet<User>();
Group group = GroupLocalServiceUtil.getGroup(layout.getGroupId());
Integer[] types = new Integer[]{Integer.valueOf(2)}; //site roles
List<Role> siteRoles = RoleLocalServiceUtil.search(group.getCompanyId(), null, types, 0, 10, null);
Set<UserGroupRole> siteUserGroupRoles = new HashSet<UserGroupRole>();
for (Iterator<Role> iterator = siteRoles.iterator(); iterator.hasNext();) {
Role siteRole = (Role) iterator.next();
List<UserGroupRole> userGroupRoles = UserGroupRoleLocalServiceUtil.getUserGroupRolesByGroupAndRole(group.getGroupId(), siteRole.getRoleId());
siteUserGroupRoles.addAll(userGroupRoles);
}
for (Iterator<UserGroupRole> it1 = siteUserGroupRoles.iterator(); it1.hasNext();) {
UserGroupRole userGroupRole = (UserGroupRole) it1.next();
User userGroupUser = userGroupRole.getUser();
siteMembers.add(userGroupUser);
}
Finally found the following solution:
Set<User> siteMembers = new HashSet<User>();
Group group = GroupLocalServiceUtil.getGroup(layout.getGroupId());
long groupId = group.getGroupId();
Integer[] types = new Integer[]{Integer.valueOf(2)}; //site roles
List<Role> siteRoles = RoleLocalServiceUtil.search(group.getCompanyId(), null, types, 0, 10, null);
Set<UserGroupGroupRole> siteUserGroupGroupRoles = new HashSet<UserGroupGroupRole>();
for (Iterator<Role> iterator = siteRoles.iterator(); iterator.hasNext();) {
Role siteRole = (Role) iterator.next();
List<UserGroupGroupRole> userGroupGroupRoles = UserGroupGroupRoleLocalServiceUtil.getUserGroupGroupRolesByGroupAndRole(groupId, siteRole.getRoleId());
siteUserGroupGroupRoles.addAll(userGroupGroupRoles);
}
for (Iterator<UserGroupGroupRole> it1 = siteUserGroupGroupRoles.iterator(); it1.hasNext();) {
UserGroupGroupRole userGroupGroupRole = (UserGroupGroupRole) it1.next();
long userGroupId = userGroupGroupRole.getUserGroupId();
List<User> userGroupUsers = UserLocalServiceUtil.getUserGroupUsers(userGroupId);
siteMembers.addAll(userGroupUsers);
}
siteMembers.addAll(UserLocalServiceUtil.getGroupUsers(groupId));
It does not seem straight-forward. I would expect a method fetching all site members, even the indirect ones through site role-user group-user mapping.
I had to fetch separately all users belonging to all user groups having a site role association with the site and on top of that fetch all users with direct membership to the site.
Any other more straight-forward solution would be welcome.
When we associate any site roles to user then association will be stored in UserGroupRole table.When ever we want get site roles then we have to use respective service class to access those roles like we need use UserGroupRoleLocalService.java class there we can find many service methods.
UserGroupRoleLocalServiceUtil.getUserGroupRolesByGroupAndRole(themeDisplay.getScopeGroupId(),supervisorRole.getRoleId());
And then you can get userId from UserGroupRole object.

In SharePoint, is it possible to programmatically get the current list of users associated with the "nt authority/authenticated users" group?

In SharePoint, I'd like to find out all of the users who have been given access to a site.
If the user is directly granted permissions, granted permissions via a SharePoint group, or granted permissions via a domain group; then I'm able to get the necessary information.
However, if the user is granted permissions via the "authenticated users" group, I am not sure how to find the list of users associated with that group.
Is this possible?
This is more of a .Net question than a Sharepoint question. Yes, you can do this - use the AD APIs to query your domain controller for a list of all users. Here is some code to get you started on programmatic AD access:
http://www.codeproject.com/KB/system/everythingInAD.aspx
You could try to do a query for all objects in AD that are Users.
Please note that this will not list any users outside of AD that might have access to the Sharepoint content. Also, if you have multiple domains, be sure to query all of the AD domains that might have access to the Sharepoint server.
Kyle, thanks for the response.
Using that information, I came up with the following to get all of the users in all of the domains:
private List<Principal> GetAllAuthenticatedUsers()
{
List<Principal> users = new List<string>();
foreach (string domain in GetAllDomains())
{
try
{
PrincipalContext context = new PrincipalContext(ContextType.Domain, domain);
// Create search condition for all enabled users
PrincipalSearcher searcher = new PrincipalSearcher();
UserPrincipal user = new UserPrincipal(context);
user.Enabled = true;
user.Name = "*";
searcher.QueryFilter = user;
// Get the users
System.DirectoryServices.AccountManagement.PrincipalSearchResult<Principal> results = searcher.FindAll();
foreach (Principal principal in results)
{
users.Add(principal);
}
}
catch
{
}
}
return users;
}
private static List<string> GetAllDomains()
{
List<string> domains = new List<string>();
using (Forest forest = Forest.GetCurrentForest())
{
foreach (Domain domain in forest.Domains)
{
domains.Add(domain.Name);
}
}
return domains;
}

SharePoint permissions for a specific group

I'm trying to establish whether a specific group has Read access to a particular site collection.
I have been trying for a day and a half but feel as if I have found three halves of different solutions!
The code fragments I have so far are:
using (SPSite site = new SPSite(this.GenerateAbsoluteUri(moduleCode, academicYear)))
{
using (SPWeb web = site.OpenWeb())
{
for (int i = web.SiteGroups.Count - 1; i >= 0; i--)
{
SPGroup group = web.SiteGroups[i];
if (Regex.IsMatch(group.Name, theGroupImLookingFor))
{
but then what?!
Most of my Google results tell me about roles but I don't know how to tie a role to a group.
Please help!
To assign permission to a user (account) or a SharePoint group there are some objects that we need to look at in a certain order. The first thing we need to do is get the the security principal that we want to assign the role to (SPUser or SPGroup). The next thing we need to do it get the actual permission (role) that we want to assign (ex: Read, Full Control etc…). Then we need to create a SPRoleAssignment object and on the constructor pass it in the SPUser or SPGroup (security principal) that we want to assign the permissions to. Now we need to add the role definition to the RoleDefinitionBindings collection of the role assignment object. Then we need to add the actual role assignment to the web (site) and update the web. Below is the full code lisitng.
// Create the site that contains our list
using(SPSite oSite = new SPSite("<<my site url>>"))
{
// Open the web object
using(SPWeb oWeb = oSite.OpenWeb())
{
// Get the group that we want to add the user to
SPGroup oGroup = oWeb.Groups["<<group name>>"];
// Get the role definition we want to assign ex: Full Control
SPRoleDefinition oRole = oWeb.RoleDefinitions["<< role name>>"];
// Create the role assignment object
SPRoleAssignment oRoleAssignment = new SPRoleAssignment(oGroup);
// Add the role definition to the role assignemnt.
// This will assign the specific permission to the security principal for this role assignemnt.
oRoleAssignment.RoleDefinitionBindings.Add(oRole);
// Now we need to add the role assignment to the web
oWeb.RoleAssignments.Add(oRoleAssignment);
// Now update the web
oWeb.Update();
}
}
Heres snippets from my own code (Sharepoint 2010).
Creating a role:
SPRoleDefinition network_role = new SPRoleDefinition();
network_role.BasePermissions = SPBasePermissions.AddListItems |
SPBasePermissions.BrowseDirectories |
SPBasePermissions.EditListItems |
SPBasePermissions.DeleteListItems;
network_role.Name = "Network - Project Member";
network_role.Description = "Provides permissions required for a member of a project.";
web.RoleDefinitions.Add(network_role);
Adding a role to a group:
var assign = new SPRoleAssignment(oweb.SiteGroups["Network Project - " + item.Code]);
assign.RoleDefinitionBindings.Add(network_role);

How can I list all SPUser objects in a SPGroup?

I need to retrieve all SPUser's from a SPGroup. Unfortunately, the group may contain Active Directory groups, so a simple SPGroup.Users is not enough (I'd just get a single SPUser for the AD group, with the IsDomainGroup property set to true).
Does anyone have a good idea how can I obtain a list of all SPUser's, descending into any Active Directory groups contained in a SPGroup? Is there an alternative to SPGroup.ContainsCurrentUser that takes a SPUser parameter?
Based on a blog post I found, I have written the following code:
private static List<SPUser> ListUsers(SPWeb web, SPPrincipal group)
{
try
{
web.Site.CatchAccessDeniedException = false;
var users = new List<SPUser>();
foreach(SPUser user in web.SiteUsers)
{
using(var userContextSite = new SPSite(web.Site.ID, user.UserToken))
{
try
{
using (var userContextWeb = userContextSite.OpenWeb(web.ID))
{
try
{
if (userContextWeb.SiteGroups[group.Name]
.ContainsCurrentUser)
users.Add(user);
}
catch (SPException)
{
// group not found, continue
}
}
}
catch(UnauthorizedAccessException)
{
// user does not have right to open this web, continue
}
}
}
return users;
}
finally
{
web.Site.CatchAccessDeniedException = true;
}
}
I don't like the fact that I have to impersonate every single user, and this code will only find AD users that have already been imported into SharePoint (so an SPUser exists for them), but that's good enough for me.
Unfortunately, it may be the case that not every member of the AD group has a corresponding SPUser object in the site (yet).
In this scenario, I'd enumerate all the members of the active directory group, and force them into the site with the SPWeb's EnsureUser() method, which returns an SPUser, and creates a new one if it doesn't already exist in the site.
For guidance on enumerating active directory members, see Get List of Users From Active Directory In A Given AD Group.

Resources