user1740721
user1740721

Reputation: 1

Check if user is a member of a group (ldap)

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.

Upvotes: 0

Views: 7074

Answers (1)

Furqan Safdar
Furqan Safdar

Reputation: 16698

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?

Upvotes: 2

Related Questions