Verify that the current user is a member of the Active Directory group

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

string CurrentUser = WindowsIdentity.GetCurrent().Name; 
+4
source share
2 answers

You can use the .NET 3.5 System.DirectoryServices.AccountManagement classes. For more information, see the MSDN Article, Managing Directory Security Principles in the .NET Framework 3.5 . "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 } } 
+11
source

Try this in .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); 
+1
source

Source: https://habr.com/ru/post/1394900/


All Articles