Use .Net DirectoryServices to Set TTL on Active Directory Group Membership

402 views Asked by At

I am using the tools in the .Net System.DirectoryServices.AccountManagement namespace to manage Active Directory groups - group creation, adding users to groups, removing users from group, etc. Here's some code that shows what I'm doing right now...

-- group creation
// connect to our organizational unit on the production Active Directory Server
using (PrincipalContext principalCtx = new PrincipalContext(ContextType.Domain, s_prodAdServerName, s_ouPath))
{
  // create group with necessary configuration and save
  using (GroupPrincipal group = new GroupPrincipal(principalCtx, groupName))
  {
    group.GroupScope = GroupScope.Local;
    group.IsSecurityGroup = true;
    group.Save();

    // group successfully created
    return true;
  }
}

-- add a member to a group
// find user on Active Directory Server
using (PrincipalContext userPrincipalCtx = new PrincipalContext(ContextType.Domain, s_userAdServerName))
{
  UserPrincipal user = UserPrincipal.FindByIdentity(userPrincipalCtx, userName);

  // if user exists, explicitly add to group on each production Active Directory server
  if (null != user)
  {
    // connect to each Active Directory Server
    foreach (string aServer in s_adServers)
    {
      // connect to our organizational unit on this server
      using (PrincipalContext groupPrincipalCtx = new PrincipalContext(ContextType.Domain, aServer, s_ouPath))
      {
        // connect to the group on this server
        using (GroupPrincipal group = GroupPrincipal.FindByIdentity(groupPrincipalCtx, groupName))
        {
          // add user to group on this server if it doesn't already exist
          if (!group.Members.Contains(user))
          {
            group.Members.Add(user);
            group.Save();
          }
        }
      }
    }

    // user is member of group on all production Active Directory Servers
    return true;
  }
  else
  {
    // user does not exist; cannot be added to group
    return false;
  }
}

My question is this: at either step outlined above (group creation or adding a user to a group), is it possible to specify the TTL for group membership. In this case, it's okay if all instances of group membership have the same TTL (in fact, that is the desired behavior), so if that configuration can somehow be set on the group that's fine, and possibly preferable. To be clear, I don't want the user to go away after the TTL, that needs to persist, I just want their membership in the group to be revoked. Thanks!

1

There are 1 answers

0
Brian Desmond On BEST ANSWER

This feature doesn't exist today but it is coming in the next version of Active Directory (the Windows 10 Server version).