Add Active Directory group user to a SharePoint Site Groups

2.4k Views Asked by At

we got a requirement to have user from Active Directory Group get added to a share point group on a regular basis. In other words we would need to syncronize the user in AD group to a Share Point group.

We are looking at a service / workflow to perform this action.

Please help us in this issue

2

There are 2 best solutions below

0
On

Perhabs you can use SPUtility.GetPrincipalsInGroup (MSDN)

bool reachedMaxCount;
SPWeb web = SPContext.Current.Web;
int limit = 100;
int group = "Domain\\SecurityGroup";
SPPrincipalInfo[] users = SPUtility.GetPrincipalsInGroup(web, group, limit, out reachedMaxCount);

There is a good example how to use: https://stackoverflow.com/a/6153943/655293

0
On

As far as I know there is no out of the box web service or workflow that performs this task. The SPUtility.GetPrincipalsInGroup method suggested by @HW90 points you definitely in the right direction.

I suggest you to write a custom SharePoint Timer Job (SPJobDefinition). Perform the desired action in the SPJobDefinition.Execute Method:

public override void Execute(Guid targetInstanceId)
{
  using (SPSite site = new SPSite("http://server/the/site/collection")
  {
    using (SPWeb web = site.OpenWeb())
    {
      int limit = 100;
      string group = "Domain\\SecurityGroup";
      SPPrincipalInfo[] users = SPUtility.GetPrincipalsInGroup(web, group, limit, out reachedMaxCount);

      SPGroup siteGroup = web.SiteGroups["TheGroup"];

      // clear the group
      for (int i = siteGroup.Users.Count - 1; i >= 0; i--)
      {
        siteGroup.Users.Remove(i);
      }

      foreach (SPPrincipalInfo pi in users)
      {
        siteGroup.AddUser(web.EnsureUser(pi.LoginName));
      }
    }
  }
}