Many organisations use their Active Directory services to assign security policies to their internal software and the one I’m currently working for is no different. The web application I’m currently developing extracts the username from the HTTP header and then queries the Active Directory service to see if that user belongs to a particular AD group. I have been implementing functionality to allow the application to add and remove users from this group and I thought I’d give a brief overview of how this is done…
The first thing you need is a service account username and password that has full control of the AD group you wish to modify, you can then implement the following to add a user to this group, just plug in the correct strings for your particular setup:
public void AddUserToRAPSGroup(string userName)
{
//Retrieve entry using LDAP
DirectoryEntry LDAPentry = new DirectoryEntry("LDAP://" + <AD Server Name>);
LDAPentry.Username = <AD Server Name> + @"\" + <AD Username>;
LDAPentry.Password = <AD Password>;
//Set up a search object using the userName as a filter
DirectorySearcher dsUser = new DirectorySearcher();
dsUser.SearchRoot = LDAPentry;
dsUser.PropertyNamesOnly = true;
dsUser.PropertiesToLoad.Add("sAMAccountName");
dsUser.Filter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=" + userName + "))";
//execute the search and retrieve the user
SearchResult srUser = dsUser.FindOne();
DirectoryEntry deUser = srUser.GetDirectoryEntry();
//now get the ad group
DirectorySearcher dsGroup = new DirectorySearcher();
dsGroup.SearchRoot = LDAPentry;
dsGroup.Filter = "(&(objectClass=group) (cn=" + <AD GroupName> + "))";
SearchResultCollection results = dsGroup.FindAll();
bool isGroupMember = false;
if (results.Count > 0)
{
DirectoryEntry group = GetDirectoryEntry(results[0].Path);
object members = group.Invoke("Members",null);
foreach ( object member in (IEnumerable) members)
{
DirectoryEntry x = new DirectoryEntry(member);
if (x.Name != deUser.Name)
{
isGroupMember = false;
}
else
{
isGroupMember = true;
break;
}
}
if (!isGroupMember)
{
group.Invoke("Add", new object[] {deUser.Path.ToString()});
}
group.Close();
}
}