LDAP:检查用户是否是组的成员

时间:2011-09-30 06:15:05

标签: c# security active-directory ldap

我在Stackoverflow和网络上发现了几个样本但是有任何工作。我想检查用户是否是特定组(或子组)的成员。当我尝试使用Active Directiory中不存在的用户名时,我会收到异常(正常,请参阅代码)

在我使用的当前代码下面:

using System;
using System.DirectoryServices;
using System.Collections.Generic;

static class Program
{
    public static string GetUserContainerName(string userName)
    {
        DirectoryEntry entry = new DirectoryEntry("LDAP://xxxxxxx:389/DC=be,DC=kb,DC=int");
        DirectorySearcher mySearcher = new DirectorySearcher(entry);
        mySearcher.Filter = string.Format("(&(sAMAccountName={0}))", userName);
        mySearcher.SearchScope = SearchScope.Subtree; //Search from base down to ALL children.
        SearchResultCollection result = mySearcher.FindAll();
        if (result.Count == 0)
            throw new ApplicationException(string.Format("User '{0}' Not Found in Active Directory.", userName));
        return result[0].GetDirectoryEntry().Name.Replace("CN=", string.Empty);
    }

    public static bool IsUserMemberOfGroup(string username, string groupname)
    {
        DirectoryEntry entry = new DirectoryEntry("LDAP://xxxxxxx.be.kb.int:389/DC=be,DC=kb,DC=int");
        DirectorySearcher mySearcher = new DirectorySearcher(entry);
        mySearcher.Filter = string.Format(String.Format("(member:1.2.840.113556.1.4.1941:=(cn={0},cn=users,DC=be,DC=kb,DC=int))", username), GetUserContainerName(username));
        mySearcher.SearchScope = SearchScope.Subtree; //Search from base down to ALL children.
        SearchResultCollection result = mySearcher.FindAll();

        for (int i = 0; i < result.Count - 1; i++)
        {
            if (result[i].Path.ToUpper().Contains(string.Format("CN={0}", groupname.ToUpper())))
                return true; //Success - group found
        }
        return false;
    }

    static void Main(string[] args)
    {
        var res = IsUserMemberOfGroup("MyUSer", "MY_GROUP_TO_CHECK");
        Console.WriteLine(res.ToString());
    }
}

2 个答案:

答案 0 :(得分:2)

为什么不使用框架中已有的内容。

看看这个:http://msdn.microsoft.com/en-us/library/fs485fwh(VS.85).aspx

WindowsIdentity identity =     WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
principal.IsInRole("role name");

答案 1 :(得分:1)

[查看Search Filter Syntax中的LDAP_MATCHING_RULE_IN_CHAIN,我还提供代码si SO的示例。

----被修改------

以下是概念证明:user1不是群组MonGrpSec2的直接成员,但属于属于MonGrpSec的{​​{1}}。代码显示您对MonGrpSec2进行分组。您可以找到用户所属的所有组(递归)。

MonGrpSec2