Query From LDAP for User Groups

那年仲夏 提交于 2019-12-28 12:34:30

问题


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


回答1:


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




回答2:


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.




回答3:


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



回答4:


Use the DirectorySearcher class to preform an ldap query.

For reference:

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




回答5:


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)




回答6:


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.



来源:https://stackoverflow.com/questions/5252108/query-from-ldap-for-user-groups

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!