I'm writing an MVC-based (.NET 4.0) website that requires login credentials from my corporate LDAP server. What my code requires is to allow only the users that are part of a certain group. As an example, I could be looking for users that are part of the "Corporate IT" group. My credentials could be part of the "System Admins" group which is a subgroup of "Corporate IT". I'm using Forms Authentication.
How would I recursively check what group a user is under when they log in?
If you want to check for the membership of a specific user, bind to the AD object in question and retrieve the tokenGroups attribute. It contains all direct and indirect group memberships in binary form - it's an array of byte arrays. Each byte array can be passed ot the constructor of the SecurityIdentifier class and subsequently being converted to an NTAccount which contains the name of the group in cleartext.
Here's a completely different solution. Tested and working on my domain. A few notes: you will have to get your DirectorySearcher.Filter correct. Add multiple OUs for your AD hierarchy (in reverse order, bottom up). Also note, to be safe, I'm disposing of a few object in "using" statements, since they implement the System.ComponentModel.Component, which in turn implements IDisposable... so, better safe than sorry.
For anybody else coming here from a search for this type of query, here is how I did it in my application:
The key is 1.2.840.113556.1.4.1941 extended search filter. Since this particular filter works with DNs only, I first get hold of DN of the user I want to check and then query groups to see if this particular user is a member of any of groups in chain.