从 LDAP 查询用户组

发布于 2024-10-20 20:58:15 字数 119 浏览 2 评论 0原文

如何在 C# .NET for ASP 中从 LDAP 活动目录获取用户的用户组。在我的场景中,我想将用户名传递给从 LDAP Active Directory 查询的方法,并告诉我我的用户是该用户组的成员。请在这方面帮助我

How To Get User group of user from LDAP active directory in C# .NET for ASP. In my Scenario I want to Pass user name to method which query from LDAP Active directory and tell me my user is Member of This User Groups. Please help me in this

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

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

发布评论

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

评论(6

℉絮湮 2024-10-27 20:58:15

如果您使用的是 .NET 3.5 或更高版本,您还可以使用新的 System.DirectoryServices.AccountManagement (S.DS.AM) 命名空间。

有了这个,您可以执行以下操作:

// create context for domain
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// find the user
UserPrincipal up = UserPrincipal.FindByIdentity(ctx, "YourUserName");

if(up != null)
{
    // get groups for that user
    var authGroups = up.GetAuthorizationGroups();
}

阅读有关新 S.DS.AM 命名空间的更多信息:

管理目录安全.NET Framework 3.5 中的主体

If you're on .NET 3.5 or newer, you can also use the new System.DirectoryServices.AccountManagement (S.DS.AM) namespaces.

With this, you can do something like:

// create context for domain
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// find the user
UserPrincipal up = UserPrincipal.FindByIdentity(ctx, "YourUserName");

if(up != null)
{
    // get groups for that user
    var authGroups = up.GetAuthorizationGroups();
}

Read more about the new S.DS.AM namespace:

Managing Directory Security Principals in the .NET Framework 3.5

我为君王 2024-10-27 20:58:15

研究使用 System.DirectoryServices 命名空间。您可以使用 DirectorySearcher 查找用户。一旦您拥有该用户的 DirectoryEntry 对象,请执行此操作:

public List<string> GetMemberOf(DirectoryEntry de)
{
  List<string> memberof = new List<string>();

  foreach (object oMember in de.Properties["memberOf"])
  {
    memberof.Add(oMember.ToString());
  }

  return memberof;
}

这将返回一个字符串列表,这些字符串是用户所属的组名称。

当然,您可以进一步细化它以包含 DirectorySearcher 代码,这样您就可以只向函数传递 samAccountName。

Look into using the System.DirectoryServices namespace. You can use a DirectorySearcher to find the user. Once you have the DirectoryEntry object for that user do this:

public List<string> GetMemberOf(DirectoryEntry de)
{
  List<string> memberof = new List<string>();

  foreach (object oMember in de.Properties["memberOf"])
  {
    memberof.Add(oMember.ToString());
  }

  return memberof;
}

This will return a list of strings which are the group names the user is a member of.

Of course you could further refine this to include the DirectorySearcher code so you can just pass the function the samAccountName.

鼻尖触碰 2024-10-27 20:58:15

试试这个...

public override string[] GetRolesForUser(string username)
    {
    var allRoles = new List<string>();
    var root = new DirectoryEntry(WebConfigurationManager.ConnectionStrings[ConnectionStringName].ConnectionString,
                                    ConnectionUsername,
                                    ConnectionPassword);

    var searcher = new DirectorySearcher(root,
                                        string.Format(CultureInfo.InvariantCulture, "(&(objectClass=user)({0}={1}))",
                                                                                    AttributeMapUsername,
                                                                                    username));

    searcher.PropertiesToLoad.Add("memberOf");
    SearchResult result = searcher.FindOne();
    if (result != null && !string.IsNullOrEmpty(result.Path))
    {
        DirectoryEntry user = result.GetDirectoryEntry();
        PropertyValueCollection groups = user.Properties["memberOf"];
        foreach (string path in groups)
        {
            string[] parts = path.Split(',');
            if (parts.Length > 0)
            {
                foreach (string part in parts)
                {
                    string[] p = part.Split('=');
                    if (p[0].Equals("cn", StringComparison.OrdinalIgnoreCase))
                    {
                        allRoles.Add(p[1]);
                    }
                }
            }
        }
    }
    return allRoles.ToArray();
}

try this...

public override string[] GetRolesForUser(string username)
    {
    var allRoles = new List<string>();
    var root = new DirectoryEntry(WebConfigurationManager.ConnectionStrings[ConnectionStringName].ConnectionString,
                                    ConnectionUsername,
                                    ConnectionPassword);

    var searcher = new DirectorySearcher(root,
                                        string.Format(CultureInfo.InvariantCulture, "(&(objectClass=user)({0}={1}))",
                                                                                    AttributeMapUsername,
                                                                                    username));

    searcher.PropertiesToLoad.Add("memberOf");
    SearchResult result = searcher.FindOne();
    if (result != null && !string.IsNullOrEmpty(result.Path))
    {
        DirectoryEntry user = result.GetDirectoryEntry();
        PropertyValueCollection groups = user.Properties["memberOf"];
        foreach (string path in groups)
        {
            string[] parts = path.Split(',');
            if (parts.Length > 0)
            {
                foreach (string part in parts)
                {
                    string[] p = part.Split('=');
                    if (p[0].Equals("cn", StringComparison.OrdinalIgnoreCase))
                    {
                        allRoles.Add(p[1]);
                    }
                }
            }
        }
    }
    return allRoles.ToArray();
}
只为一人 2024-10-27 20:58:15

使用 DirectorySearcher 类执行 ldap 查询。

供参考:

http://www.codeproject.com/KB/system/QueryADwithDotNet.aspx< /a>

Use the DirectorySearcher class to preform an ldap query.

For reference:

http://www.codeproject.com/KB/system/QueryADwithDotNet.aspx

单挑你×的.吻 2024-10-27 20:58:15

我需要一种对用户进行身份验证的方法,并检查他们是否属于特定的用户组。我通过推送用户名和密码并将“memberOf”属性加载到“搜索”实例中来完成此操作。下面的示例将显示该特定用户名的所有组。 “catch”语句将捕获错误的用户名或密码。

DirectoryEntry entry = new DirectoryEntry("LDAP://xxxxxxxx/OU=xxxxxxx,DC=xxxxxx,DC=xxxxx,DC=xxxxxx", strLdapUserName, strLdapPassword);

    try
    {
    //the object is needed to fire off the ldap connection
    object obj = entry.NativeObject;

    DirectorySearcher search = new DirectorySearcher(entry);
    search.Filter = "(SAMAccountName=" + strLdapUserName + ")";
    search.PropertiesToLoad.Add("memberOf");
    SearchResult result = search.FindOne();
    string filterAttribute = (String)result.Properties["cn"][0];

    foreach(string groupMemberShipName in result.Properties["memberOf"])
    {
        Console.WriteLine("Member of - {0}", groupMemberShipName);
    }

    }
    catch (Exception ex)
    {
    //failed to authenticate
    throw new Exception(ex.ToString());
    }

希望这有帮助。 (记得引用System.DirectoryServices)

I needed a method of authenticating a user and a check to see if they were in a specific user group. I did it by pushing the username and password and loading the "memberOf" property into the 'search' instance. Example below will display all the groups for that specific user name. The 'catch' statement will trap a wrong user name or password.

DirectoryEntry entry = new DirectoryEntry("LDAP://xxxxxxxx/OU=xxxxxxx,DC=xxxxxx,DC=xxxxx,DC=xxxxxx", strLdapUserName, strLdapPassword);

    try
    {
    //the object is needed to fire off the ldap connection
    object obj = entry.NativeObject;

    DirectorySearcher search = new DirectorySearcher(entry);
    search.Filter = "(SAMAccountName=" + strLdapUserName + ")";
    search.PropertiesToLoad.Add("memberOf");
    SearchResult result = search.FindOne();
    string filterAttribute = (String)result.Properties["cn"][0];

    foreach(string groupMemberShipName in result.Properties["memberOf"])
    {
        Console.WriteLine("Member of - {0}", groupMemberShipName);
    }

    }
    catch (Exception ex)
    {
    //failed to authenticate
    throw new Exception(ex.ToString());
    }

Hope this helps. (Remember to reference System.DirectoryServices)

温柔少女心 2024-10-27 20:58:15

我认为上面列出的大多数方法都应该有效,但我建议添加代码以确保您的代码可以“检测嵌套组成员资格中的循环循环”,如果找到,请打破您选择的脚本可能进入的任何无限循环。

I think most methods listed above should work, but i would suggest adding code to ensure that your code can "detect circular loops in nested group memberships", and if found, break any infinite loops that your script of choice could potentially get into.

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