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.
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.
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.
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.
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.
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; }
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 + "\\", "")); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With