4

I need to check whether current user is a member of an active directory group. I started with getting the current user as below. Now I want to know how to check this CurrentUser is in active directory group "CustomGroup"

string CurrentUser = WindowsIdentity.GetCurrent().Name;
Yahia
  • 69,653
  • 9
  • 115
  • 144
Deepak
  • 731
  • 4
  • 11
  • 21
  • related question: http://stackoverflow.com/questions/323536/asp-net-how-to-get-list-of-groups-in-active-directory – M.Babcock Feb 06 '12 at 00:29

2 Answers2

13

You can use the .NET 3.5 System.DirectoryServices.AccountManagement classes. See the MSDN article Managing Directory Security Principals in the .NET Framework 3.5 for details. You can use something like:

string CurrentUser = WindowsIdentity.GetCurrent().Name;

PrincipalContext context = new PrincipalContext(ContextType.Domain, "Domain");
UserPrincipal upUser = UserPrincipal.FindByIdentity(context, CurrentUser);
if(upUser != null)
{
    if (upUser.IsMemberOf(context, IdentityType.SamAccountName, "CustomGroup")) 
    {
        // The user belongs to the group
    }
}
Jeremy Cook
  • 20,840
  • 9
  • 71
  • 77
JPBlanc
  • 70,406
  • 17
  • 130
  • 175
1

Try thisin .NET 3.5 or 4:

PrincipalContext infPC = new PrincipalContext(ContextType.Domain, "domain", "login", "password");
UserPrincipal infUP = new UserPrincipal(infPC);
PrincipalSearcher infPS = new PrincipalSearcher();
UserPrincipal foundUP;
GroupPrincipal infGP = new GroupPrincipal(infPC);
GroupPrincipal foundGP;
string CurrentUser = WindowsIdentity.GetCurrent().Name;

infUP.SamAccountName = CurrentUser;
infPS.QueryFilter = infUP;
foundUP = infPS.FindOne();
infGP.Name = "CustomGroup";
infPS.QueryFilter = infGP;
foundGP = infPS.FindOne();
bool ismember = foundUP.IsMemberOf(foundGP);
pistipanko
  • 745
  • 5
  • 9
  • We know the group in which we want to search for the current user. So will there be any direct process to do it. Like get the group we want to search from AD and iterate through the users present in that group for the current user? – Deepak Feb 05 '12 at 21:09
  • This is what you wrote: "I need to check whether current user is a member of an active directory group.". So you need all users from a specific group? – pistipanko Feb 05 '12 at 21:18
  • This you need the username and password, is there some way to check if the current WindowsIdentity is a member of a group without knowing this? And without iterating over the whole group list of the identity? – TheWommies Oct 24 '13 at 03:37
  • You have to be a member of the domain which you are querying, with a specific user rights. Check here [link](http://serverfault.com/questions/167371/what-permissions-are-required-for-enumerating-users-groups-in-active-directory) or here [link](http://stackoverflow.com/questions/823184/min-security-rights-to-preform-ldap-queries-in-active-directory). – pistipanko Oct 24 '13 at 18:01