如何验证用户是否属于C#.NET中的Active Directory用户组

Rit*_*ita 1 c# active-directory

我正在编写代码来验证用户是否属于特定的AD组.

当我检查时,这是组的详细信息:

"CN=Building - 28 (ALL),OU=Exchange Auto Groups,OU=AM,OU=schwab,DC=am,DC=corp,DC=schwab,DC=com"
Run Code Online (Sandbox Code Playgroud)

如果用户(例如:user1)属于该组,则我要验证该组.

我正在尝试使用返回用户所属的组列表的方法.在这里,我必须根据集团进行过滤.

用于引入用户所属的活动目录用户组的代码:

private List<string> GetUserGroupMembership(string userName)
    {

        var directoryEntry = new DirectoryEntry();
        DirectorySearcher search = new DirectorySearcher();
     **//filter based on the username**
        search.Filter = String.Format("(cn={0})", userName);
     **//How to filter based on the Group "CN=Building - 28 (ALL),OU=Exchange Auto Groups,OU=AM,OU=schwab,DC=am,DC=corp,DC=schwab,DC=com"**
        search.PropertiesToLoad.Add("memberOf");

        List<string> groupsList = new List<string>();

        SearchResult result = search.FindOne();
        if (result != null)
        {
            int groupCount = result.Properties["memberOf"].Count;

            for (int counter = 0; counter < groupCount; counter++)
            {
                groupsList.Add((string)result.Properties["memberOf"][counter]);
            }
        }
        return groupsList.ToList();
    }
Run Code Online (Sandbox Code Playgroud)

感谢您的回复.

谢谢

Vin*_*ayC 5

如果您使用的是.NET 3.5或更高版本,请查看System.DirectoryServices.AccountManagement.这些类很容易使用.例如,

PrincipalContext pc = new PrincipalContext(ContextType.Domain);
UserPrincipal user = UserPrincipal.FindByIdentity(pc, "johndoe");
var groups = user.GetAuthorizationGroups()  // or user.GetUserGroups() 
Run Code Online (Sandbox Code Playgroud)

看看这些文章,给出了相同的一些概述:

http://anyrest.wordpress.com/2010/06/28/active-directory-c/

http://msdn.microsoft.com/en-us/magazine/cc135979.aspx#S5