Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

See if user is part of Active Directory group in C# + Asp.net

I need a way to see if a user is part of an active directory group from my .Net 3.5 asp.net c# application.

I am using the standard ldap authentication example off of msdn but I don't really see how to check against a group.

like image 981
mike_h Avatar asked Feb 03 '10 00:02

mike_h


People also ask

How do you check if a user belongs to an ad group?

You can check group membership with the Active Directory Users and Computers (ADUC) console snap-in by finding the user or group of interest and drilling down into the object's properties and clicking the “Members” or “Member Of” tab.

How do I see all members of ad group?

To get adgroupmember enabled accounts in the specified group, use the Get-AdGroupMember cmdlet to get all the members of the group and piped them to the Get-AdUser cmdlet to get enabled accounts.

Is there a way to check ad group membership for a computer?

You can check active directory group membership using the command line net user or dsget or using the Get-AdGroupMember PowerShell cmdlet to check ad group membership. Active Directory groups are a great way to manage and grant access permissions to users like access to specific servers, and computers.

How do I see what users are in a group in Windows?

Hit Windows+R, type “lusrmgr. msc” into the Run box, and then hit Enter. In the “Local Users and Groups” window, select the “Users” folder, and then double-click the user account you want to look at. In the properties window for the user account, switch to the “Member Of” tab.


2 Answers

With 3.5 and System.DirectoryServices.AccountManagement this is a bit cleaner:

public List<string> GetGroupNames(string userName) {   var pc = new PrincipalContext(ContextType.Domain);   var src = UserPrincipal.FindByIdentity(pc, userName).GetGroups(pc);   var result = new List<string>();   src.ToList().ForEach(sr => result.Add(sr.SamAccountName));   return result; } 
like image 85
Nick Craver Avatar answered Oct 01 '22 16:10

Nick Craver


Nick Craver's solution doesn't work for me in .NET 4.0. I get an error about an unloaded AppDomain. Instead of using that, I used this (we only have one domain). This will check groups of groups as well as direct group membership.

using System.DirectoryServices.AccountManagement; using System.Linq;  ...  using (var ctx = new PrincipalContext(ContextType.Domain, yourDomain)) {     using (var grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, yourGroup)) {         bool isInRole = grp != null &&              grp             .GetMembers(true)             .Any(m => m.SamAccountName == me.Identity.Name.Replace(yourDomain + "\\", ""));     } } 
like image 40
Dave Markle Avatar answered Oct 01 '22 17:10

Dave Markle