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

发布于 2024-12-07 08:29:05 字数 1956 浏览 1 评论 0原文

我在 Stackoverflow 和网络上找到了几个示例,但没有任何工作。我想检查用户是否是特定组(或子组)的成员。当我尝试使用活动目录中不存在的用户名时,出现异常(正常,请参阅代码)

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

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());
    }
}

I found several sample on Stackoverflow and over the web but any work. I'd like to check is a user is member of a specific group (or subgroup). When I try with a username who not exist in the Active Directiory, I get an Exception (normal, see the code)

Below the current code I use :

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());
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

等风来 2024-12-14 08:29:05

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

看一下:http://msdn.microsoft。 com/en-us/library/fs485fwh(VS.85).aspx

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

Why not use what is already in the framework.

Take a look at this: http://msdn.microsoft.com/en-us/library/fs485fwh(VS.85).aspx

WindowsIdentity identity =     WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
principal.IsInRole("role name");
浮萍、无处依 2024-12-14 08:29:05

[查看 搜索过滤器语法中的 LDAP_MATCHING_RULE_IN_CHAIN ,我还给出了代码示例 si 所以

----已编辑------

这是一个概念证明:user1 不是组 MonGrpSec2 的直接成员,而是属于 MonGrpSec code> 属于 MonGrpSec2。该代码显示您对 MonGrpSec2 进行分组。您可以找到用户所属的所有组(递归地)。

static void Main(string[] args)
{
  /* Connection to Active Directory
   */
  string sFromWhere = "LDAP://WM2008R2ENT:389/dc=dom,dc=fr";
  DirectoryEntry deBase = new DirectoryEntry(sFromWhere, "dom\\jpb", "passwd");

  /* To find all the groups that "user1" is a member of :
   * Set the base to the groups container DN; for example root DN (dc=dom,dc=fr) 
   * Set the scope to subtree
   * Use the following filter :
   * (member:1.2.840.113556.1.4.1941:=cn=user1,cn=users,DC=x)
   */
  DirectorySearcher dsLookFor = new DirectorySearcher(deBase);
  dsLookFor.Filter = "(member:1.2.840.113556.1.4.1941:=CN=user1 Users,OU=MonOu,DC=dom,DC=fr)";
  dsLookFor.SearchScope = SearchScope.Subtree;
  dsLookFor.PropertiesToLoad.Add("cn");

  SearchResultCollection srcGroups = dsLookFor.FindAll();

  /* Just to know if user is present in a special group
   */
  foreach (SearchResult srcGroup in srcGroups)
  {
    if (srcGroup.Path.Contains("CN=MonGrpSec2"))
      Console.WriteLine("{0}", srcGroup.Path);
  }

  Console.ReadLine();
}

[Have a look in LDAP_MATCHING_RULE_IN_CHAIN in Search Filter Syntax, I also give samples of code si SO.

----Edited------

Here is a proof of concept : user1 is not a direct member of group MonGrpSec2 but belongs to MonGrpSec that belongs to MonGrpSec2. The code show you group MonGrpSec2. You can find all the groups a user belongs to (recursively).

static void Main(string[] args)
{
  /* Connection to Active Directory
   */
  string sFromWhere = "LDAP://WM2008R2ENT:389/dc=dom,dc=fr";
  DirectoryEntry deBase = new DirectoryEntry(sFromWhere, "dom\\jpb", "passwd");

  /* To find all the groups that "user1" is a member of :
   * Set the base to the groups container DN; for example root DN (dc=dom,dc=fr) 
   * Set the scope to subtree
   * Use the following filter :
   * (member:1.2.840.113556.1.4.1941:=cn=user1,cn=users,DC=x)
   */
  DirectorySearcher dsLookFor = new DirectorySearcher(deBase);
  dsLookFor.Filter = "(member:1.2.840.113556.1.4.1941:=CN=user1 Users,OU=MonOu,DC=dom,DC=fr)";
  dsLookFor.SearchScope = SearchScope.Subtree;
  dsLookFor.PropertiesToLoad.Add("cn");

  SearchResultCollection srcGroups = dsLookFor.FindAll();

  /* Just to know if user is present in a special group
   */
  foreach (SearchResult srcGroup in srcGroups)
  {
    if (srcGroup.Path.Contains("CN=MonGrpSec2"))
      Console.WriteLine("{0}", srcGroup.Path);
  }

  Console.ReadLine();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文