0

I want to check if a user is a member of a group in c#. The application is running on windows mobile 6.1 and I have to use the ldap functions with [DllImport].

Anybody has a sample for this? Connection to the ldap server and check user/password works.

ctacke
  • 66,480
  • 18
  • 94
  • 155
user1740721
  • 1
  • 1
  • 4

1 Answers1

2

Why don't use what is already in the framework.

Take a look at this: WindowsPrincipal.IsInRole Method (String)

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

OR

If you use C# / VB.Net and System.DirectoryServices, this snippet should do the trick:

DirectoryEntry rootEntry = new DirectoryEntry("LDAP://dc=yourcompany,dc=com");

DirectorySearcher srch = new DirectorySearcher(rootEntry);
srch.SearchScope = SearchScope.Subtree;

srch.Filter = "(&(objectClass=user)(sAMAccountName=yourusername)(memberof=CN=yourgroup,OU=yourOU,DC=yourcompany,DC=com))";

SearchResultCollection res = srch.FindAll();

if(res == null || res.Count <= 0)
    Console.WriteLine("This user is NOT a member of this group");
else
    Console.WriteLine("This user is INDEED a member of this group");

Word of caution: this will only test for immediate group memberships, and it will not test for membership in what is called the "primary group" (usually "cn=Users") in your domain. It does not handle nested memberships, e.g. User A is member of Group A which is member of Group B - that fact that User A is really a member of Group B as well doesn't get reflected here.

Reference: How to write LDAP query to test if user is member of a group?

Community
  • 1
  • 1
Furqan Safdar
  • 16,260
  • 13
  • 59
  • 93
  • 1
    This question is specifically about the Compact Framework (I've clarified in the tags), which doesn't have any support for `WindowsPrincipal` or `DirectoryEntry`. – ctacke Oct 16 '12 at 11:34