0

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());
    }
}
TheBoubou
  • 19,487
  • 54
  • 148
  • 236

2 Answers2

2

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");
Stuart Blackler
  • 3,732
  • 5
  • 35
  • 60
  • What is the exception you are getting – Stuart Blackler Sep 30 '11 at 06:26
  • Better, but I have a problem. The main group is "MyMainGroup" in this group there is subgroup "MySubGroup", the user is placed in the subgroup. The checked it's on "MyMainGroup" in this case the result is false, if I use the subgroup the result is true. I have to work on the main group and do a check on the child of this one – TheBoubou Sep 30 '11 at 06:50
  • 1
    This does not work for all groups, only for some. For complete solution on how to get list of ALL groups that user is member of, check this answer on Stack Owerflow:(http://stackoverflow.com/questions/5252108/query-from-ldap-for-user-groups) – Roboblob Mar 25 '13 at 12:53
  • the problem is that this solution assumes that active directory is the implementation of LDAP. its not always the case. if im using any other LDAP server then this doesn't work. – spaceman Jun 13 '16 at 21:10
1

[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();
}
Community
  • 1
  • 1
JPBlanc
  • 70,406
  • 17
  • 130
  • 175