Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query From LDAP for User Groups

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

like image 234
Arslan Pervaiz Avatar asked Mar 09 '11 21:03

Arslan Pervaiz


2 Answers

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.

like image 38
Frank Hale Avatar answered Oct 05 '22 19:10

Frank Hale


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();
}
like image 124
piris Avatar answered Oct 05 '22 19:10

piris