пʼятниця, 1 березня 2019 р.

Get All users from SharePoint group including Active Directory group - checking AD user membership on SharePoint site

Problem: 


- to check if a user is a member of specicified SharePoint group
- user is not directly member of SharePoint group
- user is member of ActiveDirectory group
- Active Directory group is member of specicified SharePoint group.

Overview:

As we know, it's not possible to add SP Group to SP group as a member.

However, it's possible to add Active Directory group to SharePoint group.

In this case, Active Directory group appears in SharePoint group members listing as a user.
This user has specific login name with ID/guid under the hood.

Solution (with code example):


- get all users from SP group
- determine if user in SP group is Active Directory group
- if yes, get all users from Active Directory group.

Note: all code is being executed from serverside, inside SPSecurity.RunWithElevatedPrivileges block. You can read about this part more here.

Code:


1:  // TODO retrieve or pass your SPWeb object to web variable  
2:  SPWeb web = null;  
3:  SPGroup group = null;  
4:  // get group by name  
5:  try  
6:  {  
7:    group = web.SiteGroups.GetByName('[TODO Your Sharepoint Group Name]');  
8:  }  
9:  catch  
10:  {  
11:    // do nothing here  
12:  }  
13:  if (group != null)  
14:  {  
15:    // group.Users contains all users that are direct members of a group  
16:    foreach (SPUser u in group.Users)  
17:    {  
18:      // if SharePoint user is actually an Active Directory group , retrieve Active Directory members.  
19:      if( u.IsDomainGroup)  
20:      {  
21:        PrincipalContext ctx = new PrincipalContext(ContextType.Domain);  
22:        bool reachedMaxCount = false;  
23:        SPPrincipalInfo[] adUsers = SPUtility.GetPrincipalsInGroup(web, u.LoginName, int.MaxValue - 1, out reachedMaxCount);  
24:        if (adUsers != null && adUsers.Length > 0)  
25:        {  
26:          foreach (var adUser in adUsers)  
27:          {  
28:            if (adUser.PrincipalType == SPPrincipalType.User)  
29:            {  
30:              // TODO process Active Directory users here.   
31:            }else{  
32:              // TODO Active Directory group could have nested Active Directory groups.  
33:              // for sample purposes this is not covered but approach couldbe the same recursively.  
34:            }  
35:          }  
36:        }  
37:      }  
38:    }  
39:  }